Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Resizing TextField with Window

In JavaFX, how do I create a textfield inside an hbox (BorderPane layout) resize in width/length as the user resizes the window?

like image 618
noobProgrammer Avatar asked Dec 20 '22 02:12

noobProgrammer


1 Answers

You can set the HGROW for the textfield as Priority.ALWAYS.

This will enable the TextField to shrink/grow whenever the HBox changes its width.

MCVE :

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField textField = new TextField();

        HBox container  = new HBox(textField);
        container.setAlignment(Pos.CENTER);
        container.setPadding(new Insets(10));

        // Set Hgrow for TextField
        HBox.setHgrow(textField, Priority.ALWAYS);

        BorderPane pane = new BorderPane();
        pane.setCenter(container);
        Scene scene = new Scene(pane, 150, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Output :

enter image description here

like image 95
ItachiUchiha Avatar answered Dec 28 '22 09:12

ItachiUchiha