JavaFx let HBox Items use all width provided
Asked Answered
S

1

6

I have a JavaFx application and to get my specific Layout I used a few H- and VBoxes. In one HBox I have a textfield and a Button and I want that they take up all the space possible in this HBox.

vboxRight = new VBox(); //This is the right VBox
vboxRight.setSpacing(10);
   //This HBox represents the first "Line"
   hboxLine = new HBox();
   hboxLine.setSpacing(10);
   hboxLine.setMinHeight(30);
      //Textbox
      txtField = new TextField();
      txtField.setMinHeight(30);

      //Button
      btn = new Button("Search");
      btn.setMinHeight(30);
      btn.setOnAction(this);
   hboxLine.getChildren().addAll(txtField, btn);
vboxRight.getChildren().addAll(hboxLine);

Is there any way to accomplish this? maybe with css?

Salonika answered 29/11, 2017 at 22:50 Comment(4)
Post your code or FXML.Frech
It's probably HBox.setHgrow(textfield, Priority.ALWAYS); and HBox.setHgrow(button, Priority.ALWAYS);, but hard to know with out seeing the code.Frech
@SedrickJefferson the problem is, the code is pretty large and tricky, but I will post a bit.Salonika
what you need to provide is stackoverflow.com/help/mcveFestival
F
7

Using HBox.setHgrow() should solve your problem.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication50 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        VBox vboxRight = new VBox(); //This is the right VBox
        vboxRight.setSpacing(10);
        //This HBox represents the first "Line"
        HBox hboxLine = new HBox();
        hboxLine.setSpacing(10);
        hboxLine.setMinHeight(30);
        //Textbox
        TextField txtField = new TextField();
        txtField.setMinHeight(30);

        //Button
        Button btn = new Button("Search");
        btn.setMinHeight(30);
        //btn.setOnAction(this);
        HBox.setHgrow(txtField, Priority.ALWAYS);//Added this line
        HBox.setHgrow(btn, Priority.ALWAYS);//Added this line
        hboxLine.getChildren().addAll(txtField, btn);
        vboxRight.getChildren().addAll(hboxLine);

        Scene scene = new Scene(vboxRight, 300, 250);

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}

Before:

Before

After:

After

Frech answered 30/11, 2017 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.