【发布时间】:2018-08-15 09:54:28
【问题描述】:
这是我绘制巴士座位的代码。每个Button 代表在GridPane 中绘制的一个席位。当有人点击座位时,我想将座位颜色从绿色更改为黄色。到目前为止,我已经做到了。如果我单击按钮,它会在输出窗口中打印“hellow world”。但是 UI 中的按钮颜色不会改变。这是我的代码:
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;
}
【问题讨论】:
-
使用“魔术字符串”不是一个好主意。最好使用枚举。这样编译器会抱怨拼写错误,使代码更容易维护......
标签: java user-interface button javafx