首页 > 解决方案 > 使用一条语句 JavaFX 为多个按钮设置颜色

问题描述

我对 JavaFx 很陌生。我找不到压缩此代码的方法。我没有使用 fxml 或 scenebuilder。

有没有办法一次为多个对象设置颜色?或者一次创建多个对象的方法?


        Button b1 = new Button("BA1");
        Button b2 = new Button("BA2");
        Button b3 = new Button("BA3");
        Button b4 = new Button("BA4");
        Button b5 = new Button("BA5");
        Button b6 = new Button("BB6");
        Button b7 = new Button("BB7");
        Button b8 = new Button("BB8");
        Button b9 = new Button("BB9");
        Button b10 = new Button("BB10");
        Button b11 = new Button("BC11");
        Button b12 = new Button("BC12");
        Button b13 = new Button("BC13");
        Button b14 = new Button("BC14");
        Button b15 = new Button("BC15");

        b1.setStyle("-fx-background-color: blue;");
        b2.setStyle("-fx-background-color: blue;");
        b3.setStyle("-fx-background-color: blue;");
        b4.setStyle("-fx-background-color: blue;");
        b5.setStyle("-fx-background-color: blue;");
        b6.setStyle("-fx-background-color: blue;");
        b7.setStyle("-fx-background-color: blue;");
        b8.setStyle("-fx-background-color: blue;");
        b9.setStyle("-fx-background-color: blue;");
        b10.setStyle("-fx-background-color: blue;");
        b11.setStyle("-fx-background-color: blue;");
        b12.setStyle("-fx-background-color: blue;");
        b13.setStyle("-fx-background-color: blue;");
        b14.setStyle("-fx-background-color: blue;");
        b15.setStyle("-fx-background-color: blue;");

标签: javajavafx

解决方案


除了使用for循环之外,我认为 JavaFX 中没有任何东西可以做到这一点。使用for循环:

List<Button> buttons = new ArrayList<>();
for(int i = 1; i <= 15; i++){
    Button b = new Button("BA" + i);
    b.setStyle("-fx-background-color: blue;");
    buttons.add(b);
}

推荐阅读