JRadioButton


package JRadioButton;
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 MyFrame extends JFrame implements ItemListener{
    private JRadioButton radio01;
    private JRadioButton radio02;
    private String right;
    private String wrong;
    
    public MyFrame (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 JRadioButton("男人");
        radio02 = new JRadioButton("女人");
        //->添加监听
        radio01.addItemListener(this);
        radio02.addItemListener(this);
        
        //3.创建ButtonGroup来约束radioButton
        ButtonGroup btnGroup = new ButtonGroup ();
        btnGroup.add(radio01);
        btnGroup.add(radio02);
        
        //4.创建面板
        JPanel panel = new JPanel(new GridLayout(1,2,2,2));
        panel.setBorder(BorderFactory.createTitledBorder("你说我喜欢男人还是女人?"));
        panel.add(radio01);
        panel.add(radio02);
        
        this.add(panel);
    }
    
    /**ItemListener监听方法*/
    public void itemStateChanged(ItemEvent e) {
        if(e.getSource() == radio01){
            radio01.setIcon(new ImageIcon(right));
            radio02.setIcon(new ImageIcon(wrong));
        }
        else{
            radio01.setIcon(new ImageIcon(wrong));
            radio02.setIcon(new ImageIcon(right));
        }
        //每次选择后重新自动布局
        this.pack();
    }
    
    public static void main(String[] args) throws IOException {
        new MyFrame("JRadioButton");
    }
}
JRadioButton_第1张图片
JRadioButton.gif

你可能感兴趣的:(JRadioButton)