0

I have a small panel that has 3 JComboBox and 2 JCheckBox which belongs to a JButtonGroup. I am trying to check if the panel form is valid and that all required fields doesn't have a null selection so I created a method.

enter image description here

public static boolean isValid(List<Component> aComponent){
        boolean isValid = false ;
        for(Component c: aComponent){
            if(c instanceof JComboBox){
                isValid = (((JComboBox) c).getSelectedIndex() > -1);
                JOptionPane.showMessageDialog(null,"ComboBox returned: "+isValid);
            }else if(c instanceof JCheckBox){
                isValid = ( ((JCheckBox) c).isSelected() );
                JOptionPane.showMessageDialog(null,"Checkbox returned: "+isValid);
            }else if(c instanceof JTextField){
                isValid = ((JTextField) c).getText().isEmpty();
                JOptionPane.showMessageDialog(null,"TextField returned: "+isValid);
            }
        }
        return isValid;
    }

The problem is, I only need to have one selected JCheckbox for Student Type. I need to be able to check if the Button Group has at least 1 JChecBox checked.

The following block will return false since both Transferee and New are instances of JCheckBox. But I only need 1 JCheckBox checked to make the form valid.

How do I check if at least 1 is checked from the button group using my isValid() method?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
heisenberg
  • 1,784
  • 4
  • 33
  • 62
  • see: http://stackoverflow.com/questions/201287/how-do-i-get-which-jradiobutton-is-selected-from-a-buttongroup – c0der Sep 01 '16 at 03:54

1 Answers1

0

if you can change the signature of the isValid method, then you can add a new parameter to send List of ButtonGroup, then grouped components should be excluded from the first parameter List of Component .

if you dont like to do that still there is a dirty way, if it is a JCheckBox you can try to call

((DefaultButtonModel)checkBox.getModel()).getGroup()

check the "instance of" before cast to DefaultButtonModel.

hunter
  • 3,963
  • 1
  • 16
  • 19