AbstractAction lambda

时间:2017-05-13 17:02:02

标签: java swing intellij-idea lambda

IntelliJ建议我改变

new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // my code here
        }
}

(AbstractAction) (e) -> {
    // my code here
}

当我将代码更改为上面建议的代码时,我收到消息“lambda转换的目标类型必须是一个接口”。

1 个答案:

答案 0 :(得分:2)

您应该实现抽象动作类,以便在功能上使用它。

public class FunctionalAction extends AbstractAction {

    ActionListener myaction;

    public FunctionalAction(ActionListener customaction) {
        this.myaction = customaction;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        myaction.actionPerformed(e);
    }

    public ActionListener getMyaction() {
        return myaction;
    }

    public void setMyaction(ActionListener myaction) {
        this.myaction = myaction;
    }

}

您可以按如下方式使用此课程:

getTexfield().getActionMap().put(actionName, new FunctionalAction(ae -> {
        }));