Reputation: 47
I am trying to set up a method used by three different buttons. I want to load one of three different views depending on which of them is pressed. To do so, I thought about passing as an argument the button itself. But I was unable, due to javaFX not recognising the method with the new argument.
How can I get the fx:id
of the caller button so I can make the distinction between each of them? Here's what I got this far. I just need to initialize pressed
variable so it will do its thing.
if (pressed == edgeModify){
loader = new FXMLLoader(getClass().getResource("/digitalia/view/edgeView.fxml"));
} else if (pressed == sectionModify){
loader = new FXMLLoader(getClass().getResource("/digitalia/view/sectionView.fxml"));
} else {
loader = new FXMLLoader(getClass().getResource("/digitalia/view/LayerView.fxml"));
}
Upvotes: 2
Views: 1851
Reputation: 55
@FXML void handleButtonAction(ActionEvent event) {
Expression e = new Expression("");
String eventString = event.toString();
System.out.println(eventString);
String[] cutAtId = eventString.split("id=");
cutAtId = cutAtId[1].split(", ");
eventString = cutAtId[0];
System.out.println("eventString ===>>>" + eventString + "<<<<====");
}
Upvotes: -2
Reputation: 209724
Use a different handler for each button. It looks like this would be as simple as:
@FXML
private void loadEdgeView(ActionEvent event) {
load("edgeView");
}
@FXML
private void loadSectionView(ActionEvent event) {
load("sectionView");
}
@FXML
private void loadLayerView(ActionEvent event) {
load("layerView");
}
private void load(String view) {
FXMLLoader loader = new FXMLLoader("/digitalia/view/" + view + ".fxml");
// ...
}
If you really want to do this with a single method, you could leverage the userData
of the button; i.e.:
<Button text="Load Edge View" onAction="#loadView" userData="edgeView" />
<Button text="Load Section View" onAction="#loadView" userData="sectionView" />
<Button text="Load Layer View" onAction="#loadView" userData="layerView" />
and then in the controller:
@FXML
private void loadView(ActionEvent event) {
Node node = (Node) event.getSource();
String view = (String) node.getUserData();
FXMLLoader loader = new FXMLLoader("/digitalia/view/" + view + ".fxml");
// ...
}
I think using separate handlers is more maintainable, for a small price in verbosity.
Upvotes: 2
Reputation: 10640
You can use the source of the event object like this:
button.setOnAction(e -> {if (e.getSource() == button) System.out.println("button was pressed.");});
In your above example you only have to exchange pressed
with e.getSource()
.
Upvotes: 1
Reputation: 68
You can get the id of the button as below:
Button btn = (Button) event.getSource();
String id = btn.getId();
An easier approach would just be to use different handlers for the buttons.
Upvotes: 4