【问题标题】:How to get value of selected radioButton of buttonGroup如何获取buttonGroup的选定radioButton的值
【发布时间】:2014-09-13 15:37:47
【问题描述】:

如何获取所选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;
    }
}

【问题讨论】:

    标签: java swing jradiobutton buttongroup


    【解决方案1】:

    我尝试使用 buttonGroup1.getSelection().getActionCommand()

    这种方法可行,但由于某种原因,您似乎需要在创建按钮时手动设置操作命令。例如:

    JRadioButton maleButton = new JRadioButton( "Male" );
    maleButton.setActionCommand( maleButton.getText() );
    

    这对我来说确实有点像一个错误,因为如果未设置操作命令,通常操作命令默认为文本。

    【讨论】:

      【解决方案2】:

      如果您有多个按钮,您可能应该这样做:

      String getSelectedButton()
      {  
          for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
              AbstractButton button = buttons.nextElement();
              if (button.isSelected()) {
                      return button.getText();
              }
          }
          return null;
      }
      

      【讨论】:

        【解决方案3】:

        String gender=group.getSelection().getActionCommand();

        它会工作,但它显示空值。

        【讨论】:

        • 我刚刚设置了 radio1.setActionCommand("button1") 并且它会起作用(radio1 是我的 JRadioBurron 名称)
        【解决方案4】:
        int selectedRadioButtonID = radio_group.getCheckedRadioButtonId();
        // If nothing is selected from Radio Group, then it return -1
        if (selectedRadioButtonID != -1) {
        RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);
        String selectedRadioButtonText = selectedRadioButton.getText().toString();
        answerList.add(selectedRadioButtonText);
        } else {
        Toast.makeText(this, "select radio button", Toast.LENGTH_SHORT).show();
                        return false;
        }
        

        For Deatils, check this

        【讨论】:

          猜你喜欢
          • 2019-08-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-09
          相关资源
          最近更新 更多