摘自:
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();
}
}
}