简体   繁体   English

获取 JPanel 中组件的类型

[英]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.我有一个 foreach 循环,它迭代 jPanel 中的所有组件,我想获取组件的类型并检查它是否是 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?我怎样才能做到这一点?

You could use the instanceof operator, but this will give your code a bad code smell as does your entire plan.您可以使用 instanceof 运算符,但这会给您的代码带来糟糕的代码味道,就像您的整个计划一样。 Better to put the components of interest into an ArrayList for ready reference.最好将感兴趣的组件放入 ArrayList 以备参考。

Or even better, get the selected JRadioButton's ButtonModel directly from the ButtonGroup that you use to bind them together.或者更好的是,直接从用于将它们绑定在一起的 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
            }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM