[英]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.