方法一:
package HandEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class ActionEventDemo extends JFrame { JButton click; JPanel panel; JLabel message; public ActionEventDemo() { super("");//只能放在第一行,在子类的构造方法中,用super调用且放在第一行 click =new JButton ("Click"); panel =new JPanel(); message=new JLabel(); add(panel); panel.add(click); panel.add(message); actionLis al=new actionLis();//创建侦听器对象 //将监听器对象注册到事件源上 click.addActionListener(al); //但是message仍然不可识别 setSize(300,300); setVisible(true); } public static void main(String args[]) { ActionEventDemo obj=new ActionEventDemo(); } } //接口没法直接创建对象,用类实现接口 class actionLis implements ActionListener{ //该类创建的对象做监听器 @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub message.setText("Welcome to java");//需要传参 } }
分析:
该存在的问题:
方法二:接口实现体
1 package HandEvent; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 6 import javax.swing.*; 7 8 public class ActionEventDemo extends JFrame { 9 JButton click; 10 JPanel panel; 11 JLabel message; 12 13 public ActionEventDemo() { 14 super("");//只能放在第一行,在子类的构造方法中,用super调用且放在第一行 15 click =new JButton ("Click"); 16 panel =new JPanel(); 17 message=new JLabel(); 18 19 add(panel); 20 panel.add(click); 21 panel.add(message); 22 actionLis al=new actionLis();//创建侦听器对象 23 //将监听器对象注册到事件源上 24 click.addActionListener(new ActionListener(){ 25 //该类创建的对象做监听器 26 27 @Override 28 public void actionPerformed(ActionEvent arg0) { 29 // TODO Auto-generated method stub 30 message.setText("Welcome to java");//需要传参 31 32 } 33 34 }); 35 //但是message仍然不可识别 36 37 setSize(300,300); 38 setVisible(true); 39 40 41 } 42 43 public static void main(String args[]) { 44 ActionEventDemo obj=new ActionEventDemo(); 45 } 46 }
分析:
方法三:整个窗口类做监听器
1 package HandEvent; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 6 import javax.swing.*; 7 8 public class ActionEventDemo extends JFrame implements ActionListener { 9 JButton click; 10 JPanel panel; 11 JLabel message; 12 13 public ActionEventDemo() { 14 super("");//只能放在第一行,在子类的构造方法中,用super调用且放在第一行 15 click =new JButton ("Click"); 16 panel =new JPanel(); 17 message=new JLabel(); 18 19 add(panel); 20 panel.add(click); 21 panel.add(message); 22 23 // actionLis al=new actionLis();//创建侦听器对象 24 //将监听器对象注册到事件源上 25 click.addActionListener(this); 26 //但是message仍然不可识别 27 28 setSize(300,300); 29 setVisible(true); 30 31 32 } 33 34 public static void main(String args[]) { 35 ActionEventDemo obj=new ActionEventDemo(); 36 } 37 @Override 38 public void actionPerformed(ActionEvent arg0) { 39 // TODO Auto-generated method stub 40 message.setText("Welcome to java");//需要传参 41 42 } 43 }
分析:
注:直接implements:
public class ActionEventDemo extends JFrame implements ActionListener