TITLE:JComboBoxのItem選択をループ

JComboBoxのItem選択をループ

編集者:Terai Atsuhiro
作成日:2005-10-24
更新日:2023-12-24 (日) 15:31:02

概要

JComboBoxのItemの選択が、上下のカーソルキーでループするように設定します。

#screenshot

サンプルコード

 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;

解説

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

コメント