javafx中按钮颜色变化

Wal*_*man 5 java user-interface javafx button

这是我绘制公交车座位的代码。每个Button代表在 中绘制的一个座位GridPane。我想当有人点击座位时将座位颜色从绿色更改为黄色。到目前为止我已经做到了这一点。如果我单击该按钮,它会在输出窗口中打印“hellow world”。但用户界面中的按钮颜色不会改变。这是我的代码:

public static GridPane drawBus(int rows, int col, String ss){
    GridPane table = new GridPane();
    table.setHgap(5);
    table.setVgap(5);
    table.setAlignment(Pos.CENTER);
    String seatName;

    if(ss.equals("ROW WISE")||ss.equals("Row Wise")||ss.equals("row wise")){
    for(int i=0; i<rows; i++){

        for(int j=0;j<col; j++)
        {
        seat=new Button();
        seat.setAlignment(Pos.CENTER);
        seat.setPrefSize(80, 31);

        seatName=numToString(i+1)+(j+1);
        seat.setText(seatName);
        seat.setStyle("-fx-background-color: MediumSeaGreen");


        seat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            seat.setStyle("-fx-background-color: Yellow");
            System.out.println("Hello World!");

        }
        });

        busSeatList.put(seatName, 0);

        //add them to the GridPane
        table.add(seat, j, i); //  (child, columnIndex, rowIndex)

     }


    }
    }
    else
    {
      for(int i=0; i<rows; i++){

        for(int j=0;j<col; j++)
        {
        seat=new Button();
        seat.setAlignment(Pos.CENTER);
        seat.setPrefSize(80, 31);

        seatName=(i+1)+numToString(j+1);
        seat.setText(seatName);
        seat.setStyle("-fx-background-color: MediumSeaGreen");


        seat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
            //seat.setStyle("-fx-background-color: Yellow");

        }
        });



        busSeatList.put(seatName, 0);
        //add them to the GridPane
        table.add(seat, j, i); //  (child, columnIndex, rowIndex)


       }


    }


    }


    return table;
}
Run Code Online (Sandbox Code Playgroud)

fab*_*ian 5

使用已经实现此功能的类并使用样式表会更容易。ToggleButton是适合您需求的课程:

ToggleButton btn = new ToggleButton("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
    System.out.println("Hello World!");
});

...
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
Run Code Online (Sandbox Code Playgroud)

样式.css

ToggleButton btn = new ToggleButton("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
    System.out.println("Hello World!");
});

...
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
Run Code Online (Sandbox Code Playgroud)

顺便说一句:您的代码中的问题可能是使用字段 ( seat) 来存储按钮。这样,如果您按任何按钮,最后创建的将始终是修改的。final如果您想继续使用您的实现,请使用在内循环中声明的局部变量。