Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

get type of a component in a JPanel

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?

Upvotes: 0

Views: 492

Answers (2)

Michael
Michael

Reputation: 2746

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
            }
}

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

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
}

Upvotes: 3

Related Questions