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

一次设置多个按钮的样式[Javafx],java,javafx,Java,Javafx,我搜索并看到了其他几个类似的问题,但它们并没有真正回答我的问题。我有一组看起来都一样的按钮,目前我正在分别更改每个按钮的样式,如下所示: button1.setBackground(background); button1.setPrefHeight(height); button1.setPrefWidth(width); button2.setBackground(background); button2.setPrefHeight(height); button2.setPrefWidt

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

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;
但是我得到一个错误,声明“添加了重复的子项”,我假设这意味着按钮1/2/3都以某种方式指向templateButton,而不仅仅是继承templateButton的属性。有没有更好的方法,或者我应该单独设置它们?

只需使用一个循环:

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

或者创建您自己的类来扩展
按钮
并在构造函数中设置属性。

建议在JavaFX中使用CSS,最好是在外部样式表中使用CSS。除了在布局代码和样式代码之间提供良好的分离,这还允许您同时设置多个场景图节点的样式

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

.button {
    -fx-background-color: ... ;
    -fx-pref-height: ... ;
    -fx-pref-width: ... ;
}
要应用于选定的按钮组,可以为这些按钮提供样式类:

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文件中的选择器变为

.my-style {
    -fx-background-color: ... ;
    /* etc */
}
或者,如果所有按钮都位于特定布局窗格中,则可以选择布局窗格中的所有按钮:

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选择器被激活

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

button1/2/3=templateButton
将所有这些引用指向同一个对象(
templateButton
)。@Oli是的,我是这么想的,但我有一段时间没有编码了,所以我有点生疏,忘记了一些技术细节/事物的专有名称;)社区,如果你不是一个真实的人,你是如何设法发现这个问题与我提出的问题是重复的:哦,我必须说一些奇怪的东西。。