Reputation: 93
This is my code for drawing bus seat. Each Button
represents a seat drawn in the GridPane
. I want to change the seat color from green to yellow when someone clicks on the seat. So far I have done this. If I click on the button it prints "hellow world" in output window. But button color doesn't change in the UI. Here is my code:
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;
}
Upvotes: 5
Views: 43751
Reputation: 82461
It's easier to use a class that already implements this functionality and use a stylesheet. ToggleButton
is a class that suits your needs:
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;
}
BTW: the issue in your code is probably using a field (seat
) to store the button. This way if you press any button, the last one created will always be the one modified. Use a final
local variable declared in the inner loop instead if you want to keep using your implementation.
Upvotes: 5
Reputation: 4067
My advice for dynamic style is to use custom PseudoClass and css:
Pseudo class in code:
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);
});
In your css:
Button:foo {
-fx-background-color: yellow;
}
Upvotes: 3