我有一个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));;
}
}
}
但是它不起作用。
我该怎么做?
您可以使用instanceof运算符,但这将像您的整个计划一样为您的代码提供bad code smell。最好将感兴趣的组件放入ArrayList中以备参考。
或更妙的是,直接从用于将它们绑定在一起的ButtonGroup中获取选定的JRadioButton的ButtonModel。
ButtonModel selectedModel = buttonGroup.getSelection();
if (selectedModel != null) {
// use the selected button's model here
}
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
}
}