Same Size JavaFX Buttons

I have these buttons with different sizes:

Image

How can I make all buttons with the same size?

+6
source share
2 answers

It depends on the location where the button is located. For example, if you add all the buttons to a GridPane or BorderPane, you must specify each width of each corresponding variable. In the following example, I wrap all the buttons inside a VBox, set the width of the VBox preferences, and bind all the minimum button widths 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 mentioning that there are two ways to specify the size of a button. You can do this in java code or specify it in the javafx.fxml file. The above method is an example implementation of Java code.


You can also unlock the maximum button sizes so that they increase to fill the available space (unlike most nodes, by default the node button has a maximum size clamped to the preferred size, so it usually does not grow to fill the available space). The Oracle Tutorial on 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); 
+7
source

using css you can undo the preferred width of all buttons, e.g.

 .button { -fx-pref-width: 200px; } 

or create your own style for certain button groups and add a style to the button, for example: CSS:

 .my-special-button { -fx-pref-height: 28px; -fx-pref-width: 200px; } 

and then set the style to the button using FXML:

 styleClass="my-special-button" 

or in java

 myButton.getStyleClass().add("my-special-button"); 
+2
source

Source: https://habr.com/ru/post/975044/


All Articles