Swingで別のやり方でActionを実装してみる。

Swingでプログラムを作るときに、Actionクラスがやたらと多くなって困る。
せめてメソッドをボタンやメニューに登録できないかな?
と思って作ってみました。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.Method;
import javax.swing.*;

class MethodAction extends AbstractAction {
    Object obj;
    String methodName;
    MethodAction(String name, Object obj, String methodName) {
        super(name);
        this.obj = obj;
        this.methodName = methodName;
    }
    public void actionPerformed(ActionEvent e) {
        try {
            Method method = obj.getClass().getMethod(methodName, new Class[] {ActionEvent.class});
            method.invoke(obj, new Object[] {e});
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

public class MethodActionTest {
    JFrame frame;
    MethodActionTest() {
        frame = new JFrame("MethodActionのテスト");
        JButton ok = new JButton(new MethodAction("ok", this, "onOk"));
        JButton cancel = new JButton(new MethodAction("キャンセル", this, "onCancel"));
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(ok);
        frame.getContentPane().add(cancel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setVisible(true);
    }
    public void onOk(ActionEvent e) {
        JOptionPane.showMessageDialog(frame, "OKだよ");
    }
    public void onCancel(ActionEvent e) {
        JOptionPane.showMessageDialog(frame, "キャンセルだよ");
    }
    public static void main(String[] args) {
        new MethodActionTest();
    }
}

一応動きます。
MFCっぽい感じで作れますね。
*1

*1:やっぱりイマイチかなぁ。静的なチェックはできないし、デザインパターンで自明のメリットがない