JavaFX buttons with same size

蹲街弑〆低调 提交于 2019-12-05 17:39:03

问题


I have these buttons with different size:

Image

How I can make all buttons with same with size?


回答1:


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);



回答2:


using css you can override the preferred width of all buttons like

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

or create your own style class for certain button groups and add the style to the button like: css:

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

and then set the style to your button with either fxml:

styleClass="my-special-button"

or in java

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


来源:https://stackoverflow.com/questions/25754524/javafx-buttons-with-same-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!