请教一下各路高手,在java中事件的处理一下三种哪种最好,还是有更好的?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;public class Demo1 extends JFrame implements ActionListener {

JButton btn  = new JButton("方法 1");
JButton btn2 = new JButton("方法 2");
JButton btn3 = new JButton("方法 3");
Cat cat = new Cat();
public static void main(String[] args) 
{
Demo1 d1 = new Demo1();
}
public Demo1()
{
//方法1
this.btn.addActionListener(this);
//方法2
this.btn2.addActionListener(
new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {
                                        JOptionPane.showInputDialog("Btn2");
                                }
                            }
);
//方法3

this.btn3.addActionListener(this.cat);
                
                this.setLayout(new FlowLayout(FlowLayout.LEFT));
                this.getContentPane().add(this.btn);
                this.getContentPane().add(this.btn2);
                this.getContentPane().add(this.btn3);
                
                this.setVisible(true);
                this.setSize(320,200);
                this.setLocation(500,300);
                this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btn)
{
JOptionPane.showConfirmDialog(this, "Btn");
}
}}
 class Cat implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showInputDialog("Btn3");
}
}
请教一下各路高手,在java中事件的处理一下三种哪种最好,还是有更好的?

解决方案 »

  1.   

    提供给你多种方式,谈不上哪种最好,如果哪种是最好的,那其它方式不就多余了?就跟循环一样,Java不也提供了很多种循环的语句?就我个人理解:
    方法1:适用于复杂度中等场合,且能较为方便的与主类共享各种成员变量,但会增加类的复杂度;
    方法2:适用于非常简单的事件处理,那么为了方便起见,就直接用匿名类方式搞定了;
    方法3:适用于存在共享需求或者处理规则较为复杂的场合,单独拆分开来避免单个类复杂度过高。
      

  2.   

    有没比较省力气,又美观的?
    像。net那样            this.button1.Click += new System.EventHandler(this.button1_Click);
                 private void button1_Click(object sender, EventArgs e)
                {
                    Application.ExitThread();
                }
      

  3.   

    使用 javax.swing.Action / javax.swing.AbstractAction .
      

  4.   

    Action copyAction = new AbstractAction("Copy"){ 
        public void actionPerformed(ActionEvent e){...}
    };JButton copyButton = new JButton(copyAction);
    jtoolbar.add(copyAction);
    jmenu.add(copyAction);
    ...