如何检查是否选择了JRadioButton?

时间:2018-12-07 07:32:27

标签: java hibernate swing nullpointerexception jradiobutton

我尝试了

if(jRadioButton1.isSelected() ||(jRadioButton2.isSelected()) {
      jGenderGroup.getSelection().getActionCommand();
} else {
    jGndrErrorLabel.setText("Select gender.")
}  

但是控制器不会在突出显示的行之后停止,而是会前进到最后一行并抛出NullPointerException

customers.setGender(jGenderGroup.getSelection().getActionCommand());

客户属于POJO类。

我该如何摆脱呢?

3 个答案:

答案 0 :(得分:1)

尝试:)

jRadioButton1.setActionCommand("Male");  
jRadioButton2.setActionCommand("Female");
if(!jGenderGroup.isChecked()){
jLable1.setText("Please Select Gender");
}

答案 1 :(得分:0)

if(jRadioButton1.isSelected())
{
  //Male
}
else if(jRadioButton2.isSelected())
{
  //Female
}
else
{
  // no radio button has been selected
}

或更改您的代码,例如

if(jGenderGroup.getSelection() != null)
 {      
     customer.setGender(jGenderGroup.getSelection().getActionCommand())
} else {
    jGndrErrorLabel.setText("Select gender.")
}  

答案 2 :(得分:0)

我只是删除了ButtonGroup jGenderGroup
并最终为jRadioButton1jRadioButton2执行条件,而不是执行中间条件,正如我所评论的,我无法将String gender = new String();设置为
gender = jRadioButton1.getActionCommand();
由于POJO在条件块内
所以我就这样欺骗了它:

String gender = new String();
        if (jRadioButton1.isSelected()) {
            gender = jRadioButton1.getActionCommand();
        } else if (jRadioButton2.isSelected()) {
            gender = jRadioButton2.getActionCommand();
        } else {
            jGndrErrorLabel.setText("Select gender.");
            jGndrErrorLabel.setForeground(Color.red);
        } 

这就是我所期望的
感谢您的所有时间和精力。