[英]Button color change in javafx
这是我绘制巴士座位的代码。 每个Button
代表一个在GridPane
绘制的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;
}
使用已经实现此功能的类并使用样式表会更容易。 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());
.toggle-button {
-fx-background-color: green;
}
.toggle-button:selected {
-fx-background-color: yellow;
}
顺便说一句:您的代码中的问题可能是使用字段( seat
)来存储按钮。 这样,如果您按下任何按钮,最后创建的将始终是修改的那个。 如果您想继续使用您的实现,请改用在内部循环中声明的final
局部变量。
我对动态样式的建议是使用自定义 PseudoClass 和 css:
代码中的伪类:
public static final PseudoClass PSEUDO_CLASS_FOO = PseudoClass.getPseudoClass("foo");
// ... then in your creation method
// Note using java8 lambda is more concise:
seat.setOnAction(event->{
System.out.println("Hello World!");
seat.pseudoClassStateChanged(PSEUDO_CLASS_FOO, true);
});
在你的 css 中:
Button:foo {
-fx-background-color: yellow;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.