• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBoxのItem選択をループ
#navi(../)
#tags()
RIGHT:Posted by &author(aterai); at 2005-10-24
*JComboBoxのItem選択をループ [#t1a92582]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-10-24~
更新日:&lastmod;

#contents

**概要 [#s7ceec84]
JComboBoxのItemの選択が、上下のカーソルキーでループするように設定します。

#screenshot

**サンプルコード [#b3f4d4b8]
#code{{
 Action up = new AbstractAction() {
   public void actionPerformed(ActionEvent e) {
     int index = combo.getSelectedIndex();
     combo.setSelectedIndex((index==0)?combo.getItemCount()-1:index-1);
   }
 };
 Action down = new AbstractAction() {
   public void actionPerformed(ActionEvent e) {
     int index = combo.getSelectedIndex();
     combo.setSelectedIndex((index==combo.getItemCount()-1)?0:index+1);
   }
 };
 ActionMap amc = combo.getActionMap();
 amc.put("myUp",   up);
 amc.put("myDown", down);
 InputMap imc = combo.getInputMap();
 imc.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),   "myUp");
 imc.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "myDown");
}}
-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(http://lh4.ggpht.com/_9Z4BYR88imo/TQTPicRK7pI/AAAAAAAAAeI/ApRsPHlRWe0/s800/LoopComboBox.png)

**サンプルコード [#b3f4d4b8]
#code(link){{
Action up = new AbstractAction() {
  public void actionPerformed(ActionEvent e) {
    int index = combo.getSelectedIndex();
    combo.setSelectedIndex((index==0)?combo.getItemCount()-1:index-1);
  }
};
Action down = new AbstractAction() {
  public void actionPerformed(ActionEvent e) {
    int index = combo.getSelectedIndex();
    combo.setSelectedIndex((index==combo.getItemCount()-1)?0:index+1);
  }
};
ActionMap amc = combo.getActionMap();
amc.put("myUp",   up);
amc.put("myDown", down);
InputMap imc = combo.getInputMap();
imc.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),   "myUp");
imc.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "myDown");
}}

**解説 [#d842f217]
上記のサンプルでは、下のコンボボックスのActionMapとInputMapを使って、上下キーに対応する新しいアクションを設定しています。

//**参考リンク
**コメント [#fd90efef]
#comment