Liny_@NotePad

沉迷ACG中

AWT事件监听作业学习例子(1) - ActionEvent

YOYO posted @ 2008年8月11日 12:31 in 【Java SE】 with tags java AWT ActionEvent 监听 , 2520 阅读
【事件执行情况】当特定于组件的动作(比如被按下)发生时执行。
【传递的接口名】ActionListener
【需要实现方法】actionPerformed - 发生操作时调用
【样例】单击窗体中按钮文本变化

【代码】

  1. import javax.swing.*;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. public class CallByAction {
  7.  
  8.         /**
  9.          * @author Linyq.
  10.          */
  11.         public static void main(String[] args) {
  12.                 JFrame.setDefaultLookAndFeelDecorated(true);
  13.                 MyFrame frm = new MyFrame();
  14.                 frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         }
  16.  
  17. }
  18.  
  19. class MyFrame extends JFrame{
  20.        
  21.         public MyFrame(){
  22.                 this.setTitle("ActionEvent 测试");
  23.                 this.setSize(100,100);
  24.                 this.setBackground(Color.DARK_GRAY);
  25.                
  26.                 final Button btn = new Button("Call Action");
  27.                
  28.                 //      用于接收操作事件的侦听器接口:这里就是指操作按钮事件
  29.                 btn.addActionListener(new ActionListener(){
  30.  
  31.                         public void actionPerformed(ActionEvent e) {
  32.                                 //      发生操作时调用
  33.                                 if(btn.getLabel().equals("call~~!"))
  34.                                         btn.setLabel("Call Action");
  35.                                 else
  36.                                         btn.setLabel("call~~!");
  37.                         }
  38.                        
  39.                 });
  40.                 this.getContentPane().add(btn);
  41.                
  42.                 this.setVisible(true);
  43.         }
  44.        
  45. }

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter