利用反射实现事件委托类

上一篇 / 下一篇  2007-12-10 10:27:27

摘自:http://blog.csdn.net/frank_softworks/archive/2007/08/25/1758329.aspx

使用java的事件模型的例子:
    public class EventDelegate extends JFrame{
   
        public EventDelegate() {
            super();
            createAndShowGUI();
        }
   
        private void createAndShowGUI() {
            JButton button = new JButton("abc");
            button.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e){
                   System.out.println("Press");

               }
            });
            this.getContentPane().add(button);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
   
        public static void main(String[]args) {
            new EventDelegate();

        }
    }
使用事件委托类的例子:
public class EventDelegate extends JFrame{
   
    public EventDelegate() {
        super();
        createAndShowGUI();
    }
   
    private void createAndShowGUI() {
        JButton button = new JButton("abc");
        button.addActionListener(new EventHandler(this,"btn_abc"));
        this.getContentPane().add(button);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
   
    public static void main(String[]args) {
        new EventDelegate();

    }
   
    public void btn_abc(ActionEvent e) {
        System.out.println("press");
    }
}

class EventHandler implements ActionListener {
   
    //组件所在的窗体对象
    private Object form = null;
    //受到委托的方法名
    private String methodName = null;
   
    public EventHandler(Object form, String methodName) {
        this.form = form;
        this.methodName = methodName;
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        Class formType = this.form.getClass();
        try {
            Method method = formType.getMethod(methodName, new Class[]                             {e.getClass()});
            method.invoke(this.form, new Object[] {e});
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } 
}



TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-10-12  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 695
  • 日志数: 9
  • 建立时间: 2007-08-16
  • 更新时间: 2008-04-28

RSS订阅

Open Toolbar