JAVA中按钮的事件监听的三种方式

JAVA中的Swing组件,按钮的重点是进行事件的监听,可以通过调用JButton的addActionListener()方法。这个方法接受一个实现ActionListener接口的对象作为参数,ActionListener接口中只包含一个actionPerformed()方法,所以如果想把事件处理的代码与JButton进行关联,就需要如下的三种做法:

第一种:

public class Button extends MyFrame {
    private JButton
        b1 = new JButton("Button1"),
        b2 = new JButton("Button2");
    private JTextField txt = new JTextField(10);
    class ButtonListener implements ActionListener{// 定义内部类实现事件监听
        public void actionPerformed(ActionEvent e) {
            txt.setText(((JButton)e.getSource()).getText()) ;
            /*
             * String name = ((JButton)e.getSource()).getText();
             * txt.setText(name);
             */
        }
    }
    
    private ButtonListener b = new ButtonListener();
    public Button(){
        b1.addActionListener(b);
        b2.addActionListener(b);
        this.setLayout(new FlowLayout());
        this.add(b1);
        this.add(b2);
        this.add(txt);
    }
    public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Button();
            }
        });
    }
}

第二种:

//直接创建ActionListener的类的对象b,使用的是匿名内部类
    private ActionListener b= new ActionListener(){// 定义内部类实现事件监听
        public void actionPerformed(ActionEvent e) {
            txt.setText(((JButton)e.getSource()).getText()) ;
            /*
             * String name = ((JButton)e.getSource()).getText();
             * txt.setText(name);
             */
        }
        
    };

第三种:

//在程序中直接创建按钮的监听,不需要再引入监听器

 
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                txt.setText(((JButton)e.getSource()).getText());
            }
        });
        b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                txt.setText(" ");
            }
        });

 

posted on 2015-10-28 17:14  一切重来  阅读(8290)  评论(0编辑  收藏  举报

导航