Loading

【Java】javax.swing.JCheckBox 练习

 1 import java.awt.event.*;
 2 import java.awt.*;
 3 import javax.swing.*;
 4 
 5 /*
 6  * 有四个多选框,每选一项就在文本区中增加一个对应项目的名称
 7  * 取消选择,则将取消选择的项目从文本区中清除,但保留已选项目及其顺序。
 8  * */
 9 class Ex_6_1 extends JFrame implements ItemListener {
10 
11     private static final long serialVersionUID = 1L;
12     JCheckBox box1;
13     JCheckBox box2;
14     JCheckBox box3;
15     JCheckBox box4;
16     JTextArea tArea;
17     String text="";
18     String sportStr[][] = {
19             {"乒乓球","0"},
20             {"羽毛球","0"},
21             {"篮球","0"},
22             {"游泳","0"}
23     };
24     
25     Ex_6_1(){
26         box1 = new JCheckBox("乒乓球");
27         box2 = new JCheckBox("羽毛球");
28         box3 = new JCheckBox("篮球");
29         box4 = new JCheckBox("游泳");
30         tArea = new JTextArea("选择运动项目");
31         setLayout(new GridLayout(5,1));
32         setSize(300,500);
33         setTitle("多选按钮与文本区练习");
34         
35         this.add(box1); this.add(box2);this.add(box3);this.add(box4);
36         this.add(tArea);
37         
38         box1.addItemListener(this);
39         box2.addItemListener(this);
40         box3.addItemListener(this);
41         box4.addItemListener(this);
42     }
43     
44     @Override
45     /* JCheckBox要注册的事件接口是ItemListener */
46     public void itemStateChanged(ItemEvent arg0) {
47         text = ""; //每一轮点击都清空text,重新设置text字符串的内容
48         if (arg0.getItem() == box1){
49             if (sportStr[0][1] == "0") sportStr[0][1]="1";
50             else sportStr[0][1]="0"; //根据标识位反向设置
51         }else if (arg0.getItem() == box2){
52             if (sportStr[1][1] == "0") sportStr[1][1]="1";
53             else sportStr[1][1]="0";
54         }else if (arg0.getItem() == box3){
55             if (sportStr[2][1] == "0") sportStr[2][1]="1";
56             else sportStr[2][1]="0";
57         }else if (arg0.getItem() == box4){
58             if (sportStr[3][1] == "0") sportStr[3][1]="1";
59             else sportStr[3][1]="0";
60         }
61         
62         for (int i=0;i<sportStr.length;i++){
63             if (sportStr[i][1] == "1")
64                 text = text + "选择了" + sportStr[i][0] + "\n";
65         }
66         tArea.setText(text);
67     }
68 
69 }

 

posted @ 2016-03-11 14:21  uzipi  阅读(293)  评论(0编辑  收藏  举报