Reputation: 207
I get EventHandler from another class, and I want to set this EventHandler and other ActionEvent to the same button. It is possible?
The code is following. The button is: "btnAdd".
public void addActionListener(EventHandler<ActionEvent> eventHandlerSetNotSave){
btnAdd.setOnAction((e)-> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("pictures file format",
"*.TIF","*.JPG","*.PNG","*.GIF","*.JEPG");
fileChooser.getExtensionFilters().addAll(extFilter);
File file = fileChooser.showOpenDialog(null);
if (file != null &&
url.equals(emptyImageUrl)? true:alertMessageWarning("The viseme will change, and previous viseme will be delete.")) {
setImage("file:"+file.toString());
changeAfterSaved=false;
}
});
btnAdd.setOnAction(eventHandlerSetNotSave);
btnDelete.setOnAction((e)-> {
changeAfterSaved=true;
setImage(emptyImageUrl);
});
}
Upvotes: 5
Views: 10396
Reputation: 209684
Call the addEventHandler()
method instead of setOnAction(...)
:
btnAdd.addEventHandler(ActionEvent.ACTION, (e)-> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("pictures file format",
"*.TIF","*.JPG","*.PNG","*.GIF","*.JEPG");
fileChooser.getExtensionFilters().addAll(extFilter);
File file = fileChooser.showOpenDialog(null);
if (file != null &&
url.equals(emptyImageUrl)? true:alertMessageWarning("The viseme will change, and previous viseme will be delete.")) {
setImage("file:"+file.toString());
changeAfterSaved=false;
}
});
btnAdd.addEventHandler(ActionEvent.ACTION, eventHandlerSetNotSave);
Upvotes: 10
Reputation: 3534
I don't know any way you could do that with JavaFX out of the box, but there is a simple workaround. You can create a simple class to just forward your events to multiple handler like this:
public class MultipleEventHandler<T extends Event> implements
EventHandler<T> {
private Collection<EventHandler<T>> handler;
public MultipleEventHandler(Collection<EventHandler<T>> handler) {
this.handler = handler;
}
@Override
public void handle(T event) {
handler.forEach(h -> h.handle(event));
}
}
You can then pass all your event handler to the constructor and use this class as your event handler.
MultipleEventHandler<ActionEvent> handler = new MultipleEventHandler<>(asList(e, eventHandlerSetNotSave));
btnAdd.setOnAction(handler);
Upvotes: 0