2010-11-22 24 views
0

パネルにjComboBoxの束があります。パネルを循環させ、各コントロールのsetSelectedIndex(0)を設定する最良の方法は何ですか?そう等々コンテナの子コンポーネントを反復している場合jComboBoxを循環する

+0

詳しく教えてください。または利用可能なコードはありますか? –

+0

サイクルスルーはどういう意味ですか? –

答えて

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

ありがとうございました。 – Rabin

2

あなたは、各ComponentContainerのインスタンスであるかどうかをチェックすることによって、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