Liny_@NotePad

沉迷ACG中

AWT事件监听作业学习例子(2) - ItemEvent

YOYO posted @ 2008年8月12日 03:01 in 【Java SE】 with tags java AWT ActionEvent 监听 , 2694 阅读
【事件执行情况】在用户已选定项或取消选定项时执行。
【传递的接口名】ItemListener
【需要实现方法】itemStateChanged - 在用户已选定或取消选定某项时调用
【样例】选中/取消窗体中单选/复选框文本变化

【代码】

  1. import javax.swing.*;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. public class CallByItem {
  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("ItemEvent 测试");
  23.                 this.setSize(300,80);
  24.                 this.setBackground(Color.DARK_GRAY);
  25.                 this.setLayout(new FlowLayout(FlowLayout.CENTER));
  26.                
  27.                 final JCheckBox chk_box = new JCheckBox("choose it!");
  28.                 //      接收项事件的侦听器接口。
  29.                 chk_box.addItemListener(new ItemListener(){
  30.  
  31.                         public void itemStateChanged(ItemEvent e) {
  32.                                 //       在用户已选定或取消选定某项时调用。
  33.                                 if(chk_box.isSelected()){
  34.                                         chk_box.setText("you have choose it.");
  35.                                 }else{
  36.                                         chk_box.setText("choose it!");
  37.                                 }
  38.                         }
  39.                        
  40.                 });
  41.                
  42.                 this.getContentPane().add(chk_box);
  43.                
  44.                 final JRadioButton radio = new JRadioButton("radio button~");
  45.                 //      接收项事件的侦听器接口。
  46.                 radio.addItemListener(new ItemListener(){
  47.  
  48.                         public void itemStateChanged(ItemEvent e) {
  49.                                 //       在用户已选定或取消选定某项时调用。
  50.                                 if(radio.isSelected()){
  51.                                         radio.setText("check it~");
  52.                                 }else{
  53.                                         radio.setText("radio button~");
  54.                                 }
  55.                         }
  56.                        
  57.                 });
  58.                
  59.                 this.getContentPane().add(radio);
  60.                
  61.                 this.setVisible(true);
  62.         }
  63.        
  64. }

登录 *


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