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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...