事件监听及处理

事件监听及处理的方法有三种:第一种方法是只利用一个监听器以及多个if语句来决定是哪个组件产生的事件;第二种方法是使用多个内部类来响应不同组件产生的各种事件,其具体实现又分两种方式,一种是匿名内部类,一种是一般内部类。

方法一

public class test extends JFrame implements ActionListener{
  
 test{
  JButton button = new JButton();
  button.addActionListener(this);
 }
  public void actionPerformed(ActionEvent e){
   if(e.getSource == button){
     System.out.println("ok");
   }  
 }
}

对于带有文字的按钮还有另一种监听方法

JButton button = new JButton("开始");

if(e.getActionCommand().equals("开始")){
  System.out.println("开始");  
}

方法二

是将事件处理专门写成一个内部类

public class test1{
 public test1(){
  JButton button1 = new JButton("开始");
  SimpleListener listen = new SimpleListener();
  button1.addActionListener(listen);
 }
 private class SimpleListener implements ActionListener{
   public void actionPerformed(ActionEvent e){
     if(e.getActionCommand().equals("开始")){
       System.out.println("开始");
    }
  }  
 }
}

方法三

匿名内部类

JButton button2 = new JButton("开始");
button2.addActionListener(
  new ActionListener(){public void actionPerformed(ActionEvent e)
     System.out.println("开始");
                               }
);

猜你喜欢

转载自www.cnblogs.com/heibaimao123/p/9496544.html