通过jComboBox循环

通过jComboBox循环

问题描述:

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

+0

请您详细说明一下吗?或任何可用的代码? – 2010-11-22 10:07:36

+0

你是什么意思循环? – 2010-11-22 10:08:24

创建一个列表,以保持所有的组合框的轨道被添加到面板,然后遍历它们。例如:

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); 
} 
+0

非常感谢您的帮助。 – Rabin 2010-11-23 06:51:35

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

不过,我不会推荐这种“通用”的方法,因为随着时间的推移,它可能会有不可预见的结果。相反,编写一个简单的工厂方法可能是有意义的,它会创建并初始化您的JComboBox;例如

private JComboBox createCombo(Object[] items) { 
    JComboBox cb = new JComboBox(items); 

    if (items.length > 0) { 
    cb.setSelectedIndex(0); 
    } 

    return cb; 
} 

这里是万一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(); 
    } 
} 
+0

非常感谢。 – Rabin 2010-11-23 06:50:51