获得JPanel中组件的类型

问题描述 投票:0回答:2

我有一个foreach循环,可迭代jPanel中的所有组件,我想获取组件的类型并检查它是否为JRadioButton。

这是我尝试的代码:

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

但是它不起作用。

我该怎么做?

java swing jpanel components jradiobutton
2个回答
3
投票

您可以使用instanceof运算符,但这将像您的整个计划一样为您的代码提供bad code smell。最好将感兴趣的组件放入ArrayList中以备参考。

或更妙的是,直接从用于将它们绑定在一起的ButtonGroup中获取选定的JRadioButton的ButtonModel。

ButtonModel selectedModel = buttonGroup.getSelection();
if (selectedModel != null) {
 // use the selected button's model here
}

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
            }
}
© www.soinside.com 2019 - 2024. All rights reserved.