JavaFx - 设置两个' setOnAction'到同一个按钮

时间:2015-04-26 15:38:57

标签: java button javafx action

我从另一个类获取EventHandler,我想将此EventHandler和其他ActionEvent设置为相同的按钮。有可能吗?

代码如下。 按钮是:" 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);
    });
}

2 个答案:

答案 0 :(得分:7)

调用addEventHandler()方法而不是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);

答案 1 :(得分:0)

我不知道你可以用JavaFX开箱即用,但有一个简单的解决方法。您可以创建一个简单的类来将事件转发到多个处理程序,如下所示:

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));
    }
}

然后,您可以将所有事件处理程序传递给构造函数,并将此类用作事件处理程序。

MultipleEventHandler<ActionEvent> handler = new MultipleEventHandler<>(asList(e, eventHandlerSetNotSave));
btnAdd.setOnAction(handler);