TITLE:JComboBoxのアイテム履歴

Usage: #tags(tags)
Posted by at 2006-05-08

JComboBoxのアイテム履歴

JComboBoxで入力した文字列などのアイテムを順に保存します。

  • &jnlp;
  • &jar;
  • &zip;
DropDownHistory.png

サンプルコード

public boolean addItem(JComboBox combo, String str, int max) {
  if(str==null || str.length()==0) return false;
  combo.setVisible(false);
  DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel();
  model.removeElement(str);
  model.insertElementAt(str, 0);
  if(model.getSize()>max) {
    model.removeElementAt(max);
  }
  combo.setSelectedIndex(0);
  combo.setVisible(true);
  return true;
}
View in GitHub: Java, Kotlin

解説

JComboBoxに検索する文字列が入力されて、検索ボタンが押されるたびに履歴を更新しています。上記のサンプルでは、4個まで履歴を保存し、それ以上は古いものから消されます。履歴にある文字列が再度検索された場合は、それを一番上に移動しています。

コメント