Tuesday, 10 November 2020

JavaFX: When to use Pane layout

When you want absolute positioning of UI components, you can use Pane layout. Let’s see it with an example.

 

paneDemo.fxml 

<?import javafx.scene.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>

<Pane xmlns:fx="http://javafx.com/fxml" fx:controller="com.sample.app.layout.controller.PaneController"
	fx:id="pane1">

	<Rectangle fx:id="rectangle1" 
		fill="salmon"
		width="150" height="100" 
		x="50" y = "50" />

		
	<Circle fx:id="circle1" 
		centerX="350" centerY="120" 
		radius="50" 
		fill="green"/>
	
	<Ellipse fx:id="ellipse1" 
		centerX="200" centerY="250" 
		radiusX ="100" radiusY="50" 
		fill="yellow"/>
	
</Pane>

 

PaneController.java

package com.sample.app.layout.controller;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;

public class PaneController implements Initializable {

	@FXML
	private Circle circle1;

	@FXML
	private Rectangle rectangle1;
	
	@FXML
	private Ellipse ellipse1;
	
	@FXML
	private Pane pane1;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		DropShadow dropShadow = new DropShadow();
		dropShadow.setOffsetX(5);
		dropShadow.setOffsetY(5);
		dropShadow.setColor(Color.GRAY);
		
		pane1.setEffect(dropShadow);
	}

}

 

PaneDemo.java

package com.sample.app.layout;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneDemo extends Application {

	private static final String FXML_FILE = "/paneDemo.fxml";
	private static final String STAGE_TITLE = "Pane Demo";

	public static void main(String args[]) {
		launch(args);

	}

	@Override
	public void start(Stage primaryStage) throws Exception {

		Parent root = (Parent) FXMLLoader.load(this.getClass().getResource(FXML_FILE));

		Scene scene = new Scene(root, 500, 400, Color.LIGHTGRAY);

		primaryStage.setTitle(STAGE_TITLE);
		primaryStage.setScene(scene);
		primaryStage.show();
	}

}

Output

 


 

Try to resize the window, you can observe these components are positioned absolutely.

 


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment