如何获得选定的radioButton
的价值?我尝试使用buttonGroup1.getSelection().getActionCommand()
(在这里的一些答案中发布)但它不起作用。此外,我暂时使用此代码,但我想知道这是一个好习惯吗?
//Consider that maleRButton and femaleRButton are two radioButtons of
//same buttonGroup
String getGender()
{
if(maleRButton.isSelected())
{
return "Male";
}
else if(femaleRButton.isSelected())
{
return "Female";
}
else
{
return null;
}
}
我尝试使用buttonGroup1.getSelection()。getActionCommand()
这种方法可行,但出于某种原因,您似乎需要在创建按钮时手动设置操作命令。例如:
JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );
这实际上对我来说似乎是一个小错误,因为如果没有设置动作命令,通常动作命令默认为文本。
如果你有几个按钮,你可能应该这样做:
String getSelectedButton()
{
for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
String gender=group.getSelection().getActionCommand();
它会工作,但它显示空值。