日期:2014-05-20 浏览次数:20825 次
public class JRadioButtonDemo1 extends JFrame {
private boolean isEnable=false;
private final ButtonGroup genderGroup=new ButtonGroup();
private JRadioButton boyBtn=null;
private JRadioButton girlBtn=null;
public JRadioButtonDemo1(){}
public JRadioButtonDemo1(String title){
super(title);
boyBtn=new JRadioButton("boy");
girlBtn=new JRadioButton("girl");
genderGroup.add(boyBtn);
genderGroup.add(girlBtn);
Enumeration<AbstractButton> btns=genderGroup.getElements();
while(btns.hasMoreElements()){
AbstractButton btn=btns.nextElement();
btn.setEnabled(JRadioButtonDemo1.this.isEnable);
}
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(boyBtn);
this.getContentPane().add(girlBtn);
final JButton radioCtl=new JButton("enable");
radioCtl.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
if(JRadioButtonDemo1.this.isEnable){
radioCtl.setText("enable");
}else{
radioCtl.setText("disable");
}
JRadioButtonDemo1.this.isEnable=!JRadioButtonDemo1.this.isEnable;
Enumeration<AbstractButton> btns=genderGroup.getElements();
while(btns.hasMoreElements()){
AbstractButton btn=btns.nextElement();
btn.setEnabled(JRadioButtonDemo1.this.isEnable);
}
}
});
this.getContentPane().add(radioCtl);
girlBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// genderGroup.getSelection().g
System.out.println(girlBtn.getText());
System.out.println("girlBtn is selected is "+girlBtn.isSelected());
}
});
boyBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println(boyBtn.getText());
System.out.println("boyBtn is selected is "+boyBtn.isSelected());
}
});
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args){
new JRadioButtonDemo1("Demo");
}
}