关闭

GUI(二)

941人阅读 评论(0) 收藏 举报

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Gui{
 JCheckBox right1=new JCheckBox("1");
 JCheckBox right2=new JCheckBox("2");
 JCheckBox right4=new JCheckBox("4");
 JCheckBox right8=new JCheckBox("8");
    StringBuffer choices;
    JFrame frame=new JFrame("CheckBoxDemo");
    JLabel displayLabel;
    Gui()
   {
     
      right1.setMnemonic(KeyEvent.VK_4);
      right1.setSelected(true);
     
      right2.setMnemonic(KeyEvent.VK_3);
      right2.setSelected(true);
     
      right4.setMnemonic(KeyEvent.VK_2);
      right4.setSelected(true);
     
      right8.setMnemonic(KeyEvent.VK_1);
      right8.setSelected(true);
     
     
     
     
     
      CheckBoxListener myListener=new CheckBoxListener();

      right1.addItemListener(myListener);
      right2.addItemListener(myListener);
      right4.addItemListener(myListener);
      right8.addItemListener(myListener);
      choices=new StringBuffer("0000");
      displayLabel=new JLabel(choices.toString());
     
      JPanel checkPanel=new JPanel();
      checkPanel.setLayout(new GridLayout(0,1));
      checkPanel.add(right1);
      checkPanel.add(right2);
      checkPanel.add(right4);
      checkPanel.add(right8);
     
      frame.getContentPane().setLayout(new BorderLayout());
      frame.getContentPane().add(checkPanel,BorderLayout.WEST);
      frame.getContentPane().add(displayLabel,BorderLayout.CENTER);
      frame.setSize(500,500);
     
      frame.addWindowListener(new WindowAdapter(){
       public void windowClosing(WindowEvent e)
       { System.exit(0);
       }
      });
    // frame.pack(); 此处不用使用这个方法
     frame.setVisible(true);
    
 }
   
     class CheckBoxListener implements ItemListener
      { public void itemStateChanged(ItemEvent e)
        { int index=0;
          char c='-';
          Object source =e.getItemSelectable();
          if(source==right8)
          { index=0;
            c='8';
          }else if (source==right4)
          { index=1;
            c='4';
          }
          else if (source==right2)
          { index=2;
            c='2';
          }
          else if (source==right1)
          { index=3;
            c='1';
          }
          if(e.getStateChange()==ItemEvent.DESELECTED)
            c='-';
          choices.setCharAt(index,c);
          displayLabel.setText(choices.toString()); 
        }
      }
     
     
    public static void main(String s[])
      { new Gui();
      }
   
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1174453次
    • 积分:9145
    • 等级:
    • 排名:第2130名
    • 原创:120篇
    • 转载:222篇
    • 译文:1篇
    • 评论:146条
    最新评论