循环浏览jComboBox

时间:2010-11-22 09:45:06

标签: java swing

我在面板中有一堆jComboBox。循环显示面板并为每个控件设置setSelectedIndex(0)的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以通过检查每个Component是否是Component的实例来迭代Container的树,如果是,则迭代容器的子组件等等。您可以将此功能包装在ComponentIterator中,该JComboBox使用层次结构中的根组件进行初始化。这将允许您迭代组件树并将每个JComboBox初始化为特定值。

然而,我不推荐这种“通用”方法,因为随着时间的推移,随着代码的发展,它可能会出现无法预料的结果。相反,编写一个简单的工厂方法来创建和初始化private JComboBox createCombo(Object[] items) { JComboBox cb = new JComboBox(items); if (items.length > 0) { cb.setSelectedIndex(0); } return cb; } 可能是有意义的。 e.g。

ComponentIterator

以下是public class ComponentIterator implements Iterator<Component> { private final Stack<Component> components = new Stack<Component>(); /** * Creates a <tt>ComponentIterator</tt> with the specified root {@link java.awt.Component}. * Note that unless this component is a {@link java.awt.Container} the iterator will only ever return one value; * i.e. because the root component does not contain any child components. * * @param rootComponent Root component */ public ComponentIterator(Component rootComponent) { components.push(rootComponent); } public boolean hasNext() { return !components.isEmpty(); } public Component next() { if (components.isEmpty()) { throw new NoSuchElementException(); } Component ret = components.pop(); if (ret instanceof Container) { for (Component childComponent : ((Container) ret).getComponents()) { components.push(childComponent); } } return ret; } public void remove() { throw new UnsupportedOperationException(); } } 实施,以防万一:

{{1}}

答案 1 :(得分:2)

创建一个列表以跟踪添加到面板的所有组合框,然后循环它们。例如:

List<JComboBox> list = new ArrayList<JComboBox>();

JComboBox box = new JComboBox();
panel.add(box);
list.add(box); //store reference to the combobox in list

// Later, loop over the list
for(JComboBox b: list){
    b.setSelectedIndex(0);
}