java事件处理的三种方式

方法一:使用接口

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JiSuanQi extends JFrame implements ActionListener{
    JButton jb=new JButton("关闭");
    JiSuanQi(){
        this.setSize(350, 80);
        this.setLocation(300, 300);
        this.setTitle("计算器");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(jb);
        jb.addActionListener(this);
    }
    public static void main(String[] args) {
        JiSuanQi j=new JiSuanQi();
        j.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource().equals(jb)){
            System.exit(0);
        }
    }
}

方法二:定义一个类,使用接口

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JiSuanQi extends JFrame{
    JButton jb=new JButton("关闭");
    JiSuanQi(){
        this.setSize(350, 80);
        this.setLocation(300, 300);
        this.setTitle("计算器");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(jb);
        jb.addActionListener(new ButtonAction());
    }
    public static void main(String[] args) {
        JiSuanQi j=new JiSuanQi();
        j.setVisible(true);
    }
    class ButtonAction implements ActionListener{
        public void actionPerformed(ActionEvent arg0) {
            if(arg0.getSource().equals(jb)){
                System.exit(0);
            }
        }
    }
}

方法三:使用匿名内部类

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JiSuanQi extends JFrame{
    JButton jb=new JButton("关闭");
    JiSuanQi(){
        this.setSize(350, 80);
        this.setLocation(300, 300);
        this.setTitle("计算器");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(jb);
        jb.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
    }
    public static void main(String[] args) {
        JiSuanQi j=new JiSuanQi();
        j.setVisible(true);
    }
}

你可能感兴趣的:(java,事件处理)