How to get JavaFX nodes (textarea, textfield) to resize correctly when user drags to resize the stage window?

java, javafx

Solution

With a `VBox`, the components will take just enough space, vertically, to fit. After that, increase in size of the `Stage` does not make a difference.

Use `BorderPane`. If you have used Swing, this is like `BorderLayout`. This will let you place your components on the borders of the `Stage` and at the center and these components will stay where they are even after resizing.

SSCCE:

package stack;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class TextfieldAdjust extends Application {

    Scene scene;
    TextArea area;
    TextField field;
    BorderPane border;

    @Override
    public void start(Stage stage) throws Exception {
        border = new BorderPane();
        scene = new Scene(border);

        area = new TextArea();
        field = new TextField();

        area.setStyle("-fx-background-color: DARKGRAY;"
                + "-fx-text-fill: BLACK;"
                + "-fx-font-size: 14pt;");
        field.setStyle("-fx-background-color: WHEAT;"
                + "-fx-text-fill: BLACK;"
                + "-fx-font-size: 14pt;");

        border.setCenter(area);
        border.setBottom(field);

        stage.setScene(scene);
        stage.sizeToScene();
        stage.show();
    }
    public static void main(String[] args) {
        Application.launch("stack.TextFieldAdjust");
    }
}

Problem

How to get JavaFX nodes (textarea, textfield) to resize correctly when user drags to resize the stage window? I have a piece of code that creates a stage VBox with two nodes (TextArea, TextField). However, when the user drags to resize the window, these components are not dragged in proportion. Please see the pictures: Here is my code, any suggestions on how to implement a fix so that the textfield is always at the bottom, and textarea expands to fill up the white space? Thanks! ``` Stage stage = new Stage(); VBox root = new VBox(); textArea = new TextArea(); textField = new TextField(); root.getChildren().addAll(textArea, textField); textArea.setStyle("-fx-background-color: DARKGRAY;" + "-fx-text-fill: BLACK;" + "-fx-font-size: 14pt;"); textArea.setPrefSize(400, 316); textArea.setEditable(false); textArea.setWrapText(true); textField.setStyle("-fx-background-color: DARKGRAY;" + "-fx-text-fill: BLACK;" + "-fx-font-size: 14pt;"); ```

Original source