Reputation: 341
My task is to call a single method on clicking 3 buttons in javafx and that particular method execute the code that simply change the color of the button which is clicked.
According to the scene i have created 3 buttons in fxml and inside my controller i have defined a method. The code for my task is simply
myButton.setStyle("-fx-background-color:green");
Now would you please tell me that how can i get that particular button id that is clicked. Here myButton is the fx:id of the button that is clicked.
Thanks in advance.
Upvotes: 0
Views: 477
Reputation: 36792
fx:id
's are never passed to the controller. Instead they are used to inject the control's instance into the controller when your fxml gets loaded via the FXMLLoader.
When your fxml has a control
<Button fx:id="myButton">
You need to make sure that the Button reference that you create inside you controller should have the same name. If not, the instantiation of the Button will fail.
public class MyController {
@FXML
private Button myButton; // name should be same as the fx:id
...
}
Similarly, if you want to add an action on the button, you can add it on the FXML,
<Button fx:id="myButton" onAction="#myAction">
And this will look for a method with the same name in the controller. Whenever you click the button it will call the method defined in the controller.
public class MyController {
@FXML
private Button myButton; // name should be same as the fx:id
...
public void myAction(ActionEvent event) {
// Do Something
}
}
Upvotes: 0
Reputation: 11992
You could do the following:
@FXML
public void handleActionEvent(ActionEvent event) {
Object source = event.getSource();
if (source.equals(buttonA)) {
buttonA.setStyle("-fx-background-color:red");
} else if (source.equals(buttonB)) {
buttonB.setStyle("-fx-background-color:green");
} else if (source.equals(buttonC)) {
buttonC.setStyle("-fx-background-color:blue");
}
}
Having three buttons within your controller:
@FXML
private Button buttonA;
@FXML
private Button buttonB;
@FXML
private Button buttonC;
Each button needs the accordant id
and onAction="#handleActionEvent"
within the fxml.
Upvotes: 1