0

I have a foreach loop that iterates all components in a jPanel, and I want to get the type of a components and check if it's a JRadioButton.

this is the code I tried:

 for (Component c : ((Container)jPanel1).getComponents() )
 {
     if(((JRadioButton)c).isSelected() && c.getComponentType()) {
         if(!listrep.contains(((JRadioButton)c).getText())) {
             ((JRadioButton)c).setForeground(new java.awt.Color(204, 0, 0));;
         }
     }
 }

but it won't work.

How can I do that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

2 Answers2

3

You could use the instanceof operator, but this will give your code a bad code smell as does your entire plan. Better to put the components of interest into an ArrayList for ready reference.

Or even better, get the selected JRadioButton's ButtonModel directly from the ButtonGroup that you use to bind them together.

ButtonModel selectedModel = buttonGroup.getSelection();
if (selectedModel != null) {
 // use the selected button's model here
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1
for (Component c : jpanel1.getComponents()) {
            if (c instanceof JRadioButton) {
                //Do what you need to do, if you need to call JRadioButton methods
                //you will need to cast c to a JRadioButton first
            }
}
Michael
  • 2,683
  • 28
  • 30