user1236048
user1236048

Reputation: 5602

How to resize an Rectangle accordingly with a TextField?

I want to resize an Rectangle shape from JavaFX accordingly with a TextField which automatically resize on Window resize using Anchors.

I tried add anchors to the rectangle also but it won't resize from the width I set from SceneBuilder.

So short story: when my TextField resizes because my Window resize the Rectangle should resize to the same width as the TextField. Thanks

Upvotes: 2

Views: 1794

Answers (1)

Uluk Biy
Uluk Biy

Reputation: 49185

You can bind the rectangle's width to the text field's:

myRectangle.widthProperty().bind(myTextField.widthProperty());

Example:

public class Demo extends Application {

    @Override
    public void start(Stage stage) {
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);

        TextField myTextField = new TextField("default");
        Rectangle myRectangle = new Rectangle();
        myRectangle.setHeight(30);
        myRectangle.setFill(Color.AQUA);
        myRectangle.widthProperty().bind(myTextField.widthProperty());

        final VBox hb = new VBox(10);
        hb.setPadding(new Insets(5));
        hb.getChildren().addAll(myTextField, myRectangle);
        scene.setRoot(hb);
        stage.show();
    }

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

Upvotes: 3

Related Questions