代码之家  ›  专栏  ›  技术社区  ›  Rabin

循环通过jComboBox

  •  0
  • Rabin  · 技术社区  · 14 年前

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

    2 回复  |  直到 14 年前
        1
  •  2
  •   dogbane    14 年前

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

    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);
    }
    
        2
  •  2
  •   Adamski    14 年前

    你可以在 Component 通过检查每个 组成部分 Container ,如果是,则对容器的子组件进行迭代,以此类推。您可以将此功能包装为 ComponentIterator ,它由层次结构中的根组件初始化。这将允许您在组件树上迭代并初始化每个组件树 JComboBox 一个特定的值。

    然而 ,我不建议使用这种“通用”方法,因为随着时间的推移,随着代码的发展,它可能会产生不可预见的结果。相反,编写一个简单的工厂方法来创建和初始化 下拉框 ;例如。

    private JComboBox createCombo(Object[] items) {
      JComboBox cb = new JComboBox(items);
    
      if (items.length > 0) {
        cb.setSelectedIndex(0);
      }
    
      return cb;
    }
    

    这是 成分致畸剂 在有任何用途的情况下实施:

    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();
        }
    }