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+"right@2x.png";
        wrong = curPath+"wrong@2x.png";
        
        //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.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 执行rvm get stable遇到如下错误 发现是zsh的BUG, 只要进入.zshrc, 更改一下PATH就行了
    不思想者Alex阅读 1,062评论 0 2
  • 公司要做一个健康类的产品,首先解决的是信任问题。 如何让用户信任你的产品?为什么用户会信任你的产品呢?信任怎么产生...
    景深博文阅读 270评论 0 0