gpt4 book ai didi

java - 获取 JPanel 中组件的类型

转载 作者:行者123 更新时间:2023-12-01 18:37:58 25 4
gpt4 key购买 nike

我有一个 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 中以备引用。

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

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

关于java - 获取 JPanel 中组件的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21029488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com