一次设置多个按钮的样式 [Javafx]

Style multiple buttons at once [Javafx]

我搜索并看到了其他几个与此类似的问题,但它们并没有真正回答我的问题。我有一组看起来都一样的按钮,目前我正在单独更改每个按钮的样式,如下所示:

button1.setBackground(background);
button1.setPrefHeight(height);
button1.setPrefWidth(width);

button2.setBackground(background);
button2.setPrefHeight(height);
button2.setPrefWidth(width);

等等。我尝试了以下无济于事:

templateButton.setBackground(background);
templateButton.setPrefHeight(height);
templateButton.setPrefWidth(width);
button1 = templateButton;
button2 = templateButton;
button3 = templateButton;

但随后我收到一条错误消息 "duplicate children added",我假设这意味着按钮 1/2/3 都以某种方式指向 templateButton,而不是仅仅继承 templateButton 的属性。有没有更好的方法来做到这一点,还是我应该单独设置它们?

只需使用一个循环:

for (Button b : Arrays.asList(button1, button2, button3)) {
    b.setBackground(background);
    b.setPrefHeight(height);
    b.setPrefWidth(width);
}

或者创建自己的 class 扩展 Button 并在构造函数中设置属性。

在 JavaFX 中将样式应用于控件的推荐方法是使用 CSS,最好是外部样式 sheet。除了在布局代码和样式代码之间提供良好的分离外,这还允许您同时设置多个场景图节点的样式。

要应用于应用程序中的所有按钮,您可以使用

.button {
    -fx-background-color: ... ;
    -fx-pref-height: ... ;
    -fx-pref-width: ... ;
}

要应用于 select 组按钮,您可以为这些按钮指定样式 class:

Button button1 = new Button(...);
Button button2 = new Button(...);
Button button3 = new Button(...);

Stream.of(button1, button2, button3).forEach(button -> 
    button.getStyleClass().add("my-style"));

然后 css 文件中的 selector 变为

.my-style {
    -fx-background-color: ... ;
    /* etc */
}

或者,如果所有按钮都在特定布局窗格中,您可以 select 布局窗格中的所有按钮:

Button button1 = new Button(...);
Button button2 = new Button(...);
Button button3 = new Button(...);

VBox buttons = new VBox(button1, button2, button3);
buttons.getStyleClass().add("button-container");

然后 CSS select 或者是

.button-container > .button {
    /* styles.... */
}