Issue
I just created my first javaFX program. It contains 55 Buttons and I trying to find a way to get the id of the buttons that was pressed and save it into a varible without creating one handler for each button.
Edit: I managed to fill 8 GridPane's with a total of 160 buttons and every buttons gives me the name back. I added the solution in case someone is interested.
Thanks James for your time and help!
for(int i = 1; i < 9; i++ ) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 4; k++) {
String buttonText = "" + buttoncounter;
Button button = new Button(buttonText);
switch(i){
case 1: gp1.add(button, k, j);
break;
case 2: gp2.add(button, k, j);
break;
case 3: gp3.add(button, k, j);
break;
case 4: gp4.add(button, k, j);
break;
case 5: gp5.add(button, k, j);
break;
case 6: gp6.add(button, k, j);
break;
case 7: gp7.add(button, k, j);
break;
case 8: gp8.add(button, k, j);
}
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.setOnAction(e -> {
buttonPressed = Integer.parseInt(buttonText);
});
buttoncounter++;
}
}
}
Solution
You should create the buttons programmatically (i.e. not in FXML). That way you can easily register a different handler with each, and you don't need to look up the button by id or via its text, etc.
For example, in your FXML file, do
<TilePane fx:id="buttonPane" />
And then in the controller:
public class Controller {
@FXML
private TilePane buttonPane ;
public void initialize() {
for (int i = 1 ; i <= 55 ; i++) {
String buttonText = "Button "+i ;
Button button = new Button(buttonText);
buttonPane.getChildren().add(button);
button.setOnAction(e -> {
// whatever you need here: you know the button pressed is the
// one and only button the handler is registered with
System.out.println(buttonText + " clicked");
});
}
}
// ...
}
Answered By - James_D
Answer Checked By - Katrina (JavaFixing Volunteer)