Swing/DropDownHistory のバックアップの現在との差分(No.1)
TITLE:JComboBoxのアイテム履歴
JComboBoxのアイテム履歴
編集者:Terai Atsuhiro~
作成日:2006-05-08
更新日:2021-02-16 (火) 17:07:06
概要
JComboBox
で入力した文字列などのアイテムを順に保存します。
Screenshot
Advertisement
概要
JComboBoxで入力した文字列などのアイテムを順に保存します。サンプルコード
#spanend
#spanadd
public static boolean addItem(JComboBox<String> combo, String str, int max) {
#spanend
if (Objects.isNull(str) || str.isEmpty()) {
return false;
}
combo.setVisible(false);
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) combo.getModel();
model.removeElement(str);
model.insertElementAt(str, 0);
if (model.getSize() > max) {
model.removeElementAt(max);
}
combo.setSelectedIndex(0);
combo.setVisible(true);
return true;
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin#screenshot
解説
上記のサンプルでは、JComboBox
に検索する文字列が入力されて検索ボタンが押されるたびに履歴を更新しています。
サンプルコード
#spanend
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;
}
#spandel
- &jnlp;
- &jar;
- &zip;
-
4
個まで履歴を保存しそれ以上は古いものから削除 - 履歴にある文字列が再度検索された場合はそれを一番上に移動