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.

rect.widthProperty().bind(scene.widthProperty().subtract(20));

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 http://java-buddy.blogspot.com/
*/
public class JavaFXRect extends Application {

@Override
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.setText("java-buddy.blogspot.com");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});

//Create Rectangle with RectangleBuilder
Rectangle rect = RectangleBuilder
.create()
.width(scene.getWidth() - 20)
.height(50)
.fill(Color.AZURE)
.stroke(Color.rgb(150, 150, 150))
.strokeWidth(3)
.build();

//adjust rect width follow scene resizing
rect.widthProperty().bind(scene.widthProperty().subtract(20));

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

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

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


No comments:

Post a Comment