【问题标题】:get type of a component in a JPanel获取 JPanel 中组件的类型
【发布时间】:2014-01-28 13:13:17
【问题描述】:

我有一个迭代 jPanel 中所有组件的 foreach 循环,我想获取组件的类型并检查它是否是 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));;
         }
     }
 }

但它不会起作用。

我该怎么做?

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖MCVE
  • @AndrewThompson:啊,一个 MCVE,对我来说是一个新的,感谢您显示此链接!

标签: java swing jpanel components jradiobutton


【解决方案1】:

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

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

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

【讨论】:

  • 喜欢该链接中的引用。
【解决方案2】:
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
            }
}

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2012-08-18
    • 2018-02-23
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2018-08-31
    • 2016-09-25
    相关资源
    最近更新 更多