JavaFX buttons with same size


Question

I have these buttons with different size:

Image

How I can make all buttons with same with size?

1
9
9/9/2014 10:26:09 PM

It depends on layout where the button is located. For example, if you add all the buttons into GridPane or BorderPane, you have to specify each button width to correspond to certain variable. In the following example I wrap all buttons inside VBox, set VBox preference width and tie up all buttons minimum width to it:

VBox vBox = new VBox();
vBox.setPrefWidth(100);

Button btn1 = new Button("Short");
Button btn2 = new Button("Super Long Button");

btn1.setMinWidth(vBox.getPrefWidth());
btn2.setMinWidth(vBox.getPrefWidth());

vBox.getChildren().addAll(btn1, btn2);

It is also worth to mention that there are two ways to specify the button size. You can do it in the java code or specify it in javafx .fxml file. The above method is an example for java code implementation.


You can also unclamp a button's maximum dimensions so it will grow to fill the available space (unlike most nodes, by default a button node has it's max size clamped to it's preferred size so it doesn't usually grow to fill available space). An Oracle tutorial on Tips for Sizing and Aligning Nodes explains this in more detail.

VBox vBox = new VBox();

Button btn1 = new Button("Short");
Button btn2 = new Button("Super Long Button");

btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);

vBox.getChildren().addAll(btn1, btn2);
8
9/10/2014 5:52:19 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon