JCheckBox



package JCheckBox;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import javax.swing.*;

public class JCheckBoxDemo extends JFrame implements ItemListener{
    private JCheckBox radio01,radio02,radio03;
    private String right;
    private String wrong;
    
    public JCheckBoxDemo (String title) throws IOException{
        super (title);
        //只需要设置位置即可
        this.setLocation(200,200);
        //创建子组件
        this.createComponents();
        //监听窗口关闭
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(1);
            }
        });
        this.pack();
        this.setVisible(true);
    }
    
    /**创建子组件
     * @throws IOException */
    private void createComponents() throws IOException{
        //1.创建候选图片
        //->获取当前项目路径
        String curPath = getClass().getResource(".").getFile().toString();
        //->转码
        curPath = URLDecoder.decode(curPath,"UTF-8");
        right = curPath+"[email protected]";
        wrong = curPath+"[email protected]";
        
        //2.创建radioButton并注册监听
        radio01 = new JCheckBox("男人");
        radio02 = new JCheckBox("女人");
        radio03 = new JCheckBox("人妖");
        //->添加监听
        radio01.addItemListener(this);
        radio02.addItemListener(this);
        radio03.addItemListener(this);
        
        //3.创建面板
        JPanel panel = new JPanel(new GridLayout(1,3,2,2));
        panel.setBorder(BorderFactory.createTitledBorder("你说我喜欢男人还是女人?"));
        panel.add(radio01);
        panel.add(radio02);
        panel.add(radio03);
        
        this.add(panel);
    }
    
    /**ItemListener监听方法*/
    public void itemStateChanged(ItemEvent e) {
        JCheckBox checkBox = (JCheckBox)e.getItem();
        
        /*
         e.getItem():Returns the item affected by the event.
         就是返回在对应事件下当前操作的对象,要么是选中要么是没选中
         */
        if (checkBox.isSelected()){
            checkBox.setIcon(new ImageIcon(right));
        }else{
            checkBox.setIcon(new ImageIcon(wrong));
        }
        
        //在每次选择后,重新设置frame的大小
        this.pack();
    }
    
    public static void main(String[] args) throws IOException {
        new JCheckBoxDemo("JCheckBox");
    }
    
}
JCheckBox_第1张图片
demo.gif

你可能感兴趣的:(JCheckBox)