这是我绘制公交车座位的代码。每个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;
}
使用已经实现此功能的类并使用样式表会更容易。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());
样式.css
.toggle-button {
-fx-background-color: green;
}
.toggle-button:selected {
-fx-background-color: yellow;
}
顺便说一句:您的代码中的问题可能是使用一个字段(seat
)来存储按钮。这样如果你按any按钮,最后创建的将始终是修改的。用一个final
如果您想继续使用您的实现,请在内部循环中声明局部变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)