I have a HBox and two (or more) Button's in it. And I want all the buttons be of the same width. I can't set width of the buttons in pixels because texts are taken from resource bundle for every language (so length of the text is variable). This is the code I tried, but didn't succeed:
Button but1=new Button("Long text");
Button but2=new Button ("Text");
HBox.setHgrow(but1, Priority.ALWAYS);
HBox.setHgrow(but2, Priority.ALWAYS);
HBox hbox=new HBox();
hbox.getChildren().addAll(but1,but2);
Scene scene=new Scene(hbox, 1000, 600);
stage.setScene(scene);
stage.show();
What is my mistake?
Button SizeThe methods setMinWidth() and setMaxWidth() sets the minimum and maximum width the button should be allowed to have. The method setPrefWidth() sets the preferred width of the button. When there is space enough to display a button in its preferred width, JavaFX will do so.
To add some buttons to the HBox use the getChildren(). add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.
The JavaFX HBox component is a layout component which positions all its child nodes (components) in a horizontal row. The Java HBox component is represented by the class javafx. scene.
HBox and VBox containers are used to layout the containers nested within them either horizontally from left to right (HBox) or vertically from top to bottom (VBox). Containers are packed in the HBox or VBox container in the order in which they appear in the structure.
You need to set the maxWidth
of the Button to Double.MAX_VALUE
and also set HBox.setHgrow()
to Priority.ALWAYS
to make the Button fill the available width in the HBox.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button but1 = new Button("Long text");
Button but2 = new Button ("Text");
HBox hbox=new HBox();
hbox.getChildren().addAll(but1,but2);
but1.setMaxWidth(Double.MAX_VALUE);
but2.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(but1, Priority.ALWAYS);
HBox.setHgrow(but2, Priority.ALWAYS);
Scene scene=new Scene(hbox, 1000, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch();
}
}
Set button maximum width to maximum value:
but1.setMaxWidth(Double.MAX_VALUE);
But it will only resize buttons to fill hbox width. If you need buttons with the same width, you should find the longest button and then set its width to other buttons.
but1.setPrefWidth(width);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With