Sunday, June 16, 2013

Auto adjust width of Rectangle when parent resized

Last post demonstrate how to "Create Rectangle with width according to parent". It define width of the Rectangle when it was built. When the parent window resized, it will not follow.

To make width of the Rectangle, rect, follow parent window resizing automatically, we can call rect.widthProperty().bind() with parent's widthProperty.


Auto adjust width of Rectangle when parent resized
Auto adjust width of Rectangle when parent resized

package javafxrect;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.stage.Stage;

 * @web
public class JavaFXRect extends Application {
    public void start(Stage primaryStage) {
        //Group root = new Group();
        VBox root = new VBox(5);    // spacing = 5
        root.setPadding(new Insets(10, 10, 10, 10));
        Scene scene = new Scene(root, 300, 250);
        Button btn = new Button();
        btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
        //Create Rectangle with RectangleBuilder
        Rectangle rect = RectangleBuilder
                .width(scene.getWidth() - 20)
                .stroke(Color.rgb(150, 150, 150))
        //adjust rect width follow scene resizing

        root.getChildren().addAll(rect, btn);

        primaryStage.setTitle("Hello World!");

    public static void main(String[] args) {

No comments:

Post a Comment