初学GUI对RadionButton组的选定RadioButton的获取找了几个方法:
一:用循环把按钮添加到组内,找选取值时再用一个循环。
//创建单选按钮组
private JRadioButton rb[];
String[] sex = {"male","female"};
ButtonGroup bg = new ButtonGroup();
rb = new JRadioButton[sex.length]
for(int i=0; i < sex.length; i++){
rb[i] = new JRadioButton(sex[i]);
bg.add(rb[i]);
}
//获取选取值
for(int i=0;i<rb.length;i++){
String str = "";
if(rb[i].isSelected())
str += rb[i].getText();
}
——这个方法来自《Java面向对象程序设计基础教程》
二:写一个RadioButtonList类,再提供getResults()方法来获取值
import javax.swing.*;
public class RadioButtonList extends JPanel{
String[] items = null;
JRadioButton[] jrbs = null;
public RadioButtonList(String[] items){
this.items = items;
ButtonGroup bg = new ButtonGroup();
jrbs = new JRadioButton[items.length];
for(int i = 0; i < jrbs.length;i++){
jrbs[i] = new JRadioButton(this.items[i]);
add(jrbs[i]);
bg.add(jrbs[i]);
}
}
public String getResults(){
String results = "";
for(JRadioButton jrb : jrbs){
if(jrb.isSelected()){
results = jrb.getText();
break;
}
}
return results;
}
}
——这个方法来自《Java通用范例开发金典》