初始化:java
勾選以後this
源代碼:spa
<span style="font-size:14px;">import java.io.File ; import java.awt.event.WindowEvent ; import java.awt.event.WindowListener ; import java.awt.event.WindowAdapter ; import java.awt.event.ItemEvent ; import java.awt.Container ; import java.awt.event.ItemListener ; import java.awt.GridLayout ; import javax.swing.JFrame ; import javax.swing.JCheckBox ; import javax.swing.JPanel ; import javax.swing.ImageIcon ; import javax.swing.BorderFactory ; class MyItemListener implements ItemListener { private String right = "d:"+File.separator+"right.png" ; private String wrong = "d:"+File.separator+"wrong.gif" ; public void itemStateChanged(ItemEvent e) { JCheckBox jcb = (JCheckBox)e.getItem() ; { if(jcb.isSelected()) { jcb.setIcon(new ImageIcon(right)) ; }else jcb.setIcon(new ImageIcon(wrong)) ; } } } ; class MyCheckBox { private JFrame frame = new JFrame() ; private String wrong = "d:"+File.separator+"wrong.gif" ; private Container con = frame.getContentPane() ; private JPanel pan = new JPanel() ; JCheckBox jcb1 = new JCheckBox("學生",new ImageIcon(wrong)) ; JCheckBox jcb2 = new JCheckBox("成年人",new ImageIcon(wrong)) ; JCheckBox jcb3 = new JCheckBox("男孩",new ImageIcon(wrong)) ; public MyCheckBox() { pan.setBorder(BorderFactory.createTitledBorder("選擇人物屬性")) ; pan.setLayout(new GridLayout(1,3)) ; pan.add(jcb1) ; pan.add(jcb2) ; pan.add(jcb3) ; jcb1.addItemListener(new MyItemListener()) ; jcb2.addItemListener(new MyItemListener()) ; jcb3.addItemListener(new MyItemListener()) ; con.add(pan) ; this.frame.setSize(300,300) ; this.frame.setVisible(true) ; this.frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(1) ; } }) ; } } ; class Tester { public static void main(String args[]) { new MyCheckBox() ; } } </span>