java SWing事件调用的两种机制

[java] view plain copy
 
  1. /** 
  2. * java swing中事件调用的两种机制: 
  3. * (一)响应机制 
  4. * (二)回调机制 
  5. */  
  6. package test;  
  7.   
  8. import java.awt.*;  
  9. import java.awt.event.*;  
  10. import javax.swing.*;  
  11.   
  12. class SimpleListener implements ActionListener {  
  13.     /* 
  14.      * 利用该类来监听事件源产生的事件,利用响应机制 
  15.      */  
  16.     public void actionPerformed(ActionEvent e) {  
  17.         String buttonName = e.getActionCommand();  
  18.         if (buttonName.equals("按钮1"))  
  19.             System.out.println("按钮1 被点击");  
  20.   
  21.     }  
  22. }  
  23.   
  24. /* 
  25. * 利用该类来处理事件源产生的事件,利用回调机制 
  26. */  
  27. class ButtonAction extends AbstractAction {  
  28.   
  29.     public void actionPerformed(ActionEvent e) {  
  30.         System.out.println("按钮2 被点击");  
  31.     }  
  32. }  
  33.   
  34.   
  35. public class ActionTest {  
  36.     private static JFrame frame; // 定义为静态变量以便main使用  
  37.     private static JPanel myPanel; // 该面板用来放置按钮组件  
  38.     private JButton button1; // 这里定义按钮组件  
  39.     private JButton button2;  
  40.   
  41.     public ActionTest() { // 构造器, 建立图形界面  
  42.         // 新建面板  
  43.         myPanel = new JPanel();  
  44.         // 新建按钮  
  45.         button1 = new JButton("按钮1"); // 新建按钮1  
  46.         // 建立一个actionlistener让按钮1注册,以便响应事件  
  47.         SimpleListener ourListener = new SimpleListener();  
  48.         button1.addActionListener(ourListener);  
  49.   
  50.         button2 = new JButton();// 新建按钮2  
  51.         // 建立一个ButtonAction注入按钮2,以便响应事件  
  52.         ButtonAction action = new ButtonAction();  
  53.         button2.setAction(action);  
  54.         button2.setText("按钮2");  
  55.   
  56.         myPanel.add(button1); // 添加按钮到面板  
  57.         myPanel.add(button2);  
  58.     }  
  59.   
  60.   
  61.     public static void main(String s[]) {  
  62.         ActionTest gui = new ActionTest(); // 新建Simple1组件  
  63.   
  64.         frame = new JFrame("Simple1"); // 新建JFrame  
  65.         // 处理关闭事件的通常方法  
  66.         frame.addWindowListener(new WindowAdapter() {  
  67.             public void windowClosing(WindowEvent e) {  
  68.                 System.exit(0);  
  69.             }  
  70.         });  
  71.   
  72.         frame.getContentPane().add(myPanel);  
  73.         frame.pack();  
  74.         frame.setVisible(true);  
  75.     }  
  76. }  


 
1
原文地址:https://www.cnblogs.com/jiangzhaowei/p/7448866.html