• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBoxのアイテム履歴
#navi(../)
*JComboBoxのアイテム履歴 [#x6756518]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-05-08~
更新日:&lastmod;
---
category: swing
folder: DropDownHistory
title: JComboBoxのアイテム履歴
tags: [JComboBox]
author: aterai
pubdate: 2006-05-08T08:25:26+09:00
description: JComboBoxで入力した文字列などのアイテムを順に保存します。
image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTL-2krEbI/AAAAAAAAAYc/9yTnbMmSi1Q/s800/DropDownHistory.png
---
* 概要 [#summary]
`JComboBox`で入力した文字列などのアイテムを順に保存します。

#contents
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTL-2krEbI/AAAAAAAAAYc/9yTnbMmSi1Q/s800/DropDownHistory.png)

**概要 [#ie305259]
JComboBoxで入力した文字列などのアイテムを順に保存します。
* サンプルコード [#sourcecode]
#code(link){{
public static boolean addItem(JComboBox<String> combo, String str, int max) {
  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;
}
}}

#screenshot
* 解説 [#explanation]
上記のサンプルでは、`JComboBox`に検索する文字列が入力されて検索ボタンが押されるたびに履歴を更新しています。

**サンプルコード [#b09ed436]
#code{{
 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;
 }
}}
-&jnlp;
-&jar;
-&zip;
- `4`個まで履歴を保存しそれ以上は古いものから削除
- 履歴にある文字列が再度検索された場合はそれを一番上に移動

**解説 [#r024d364]
JComboBoxに検索する文字列が入力されて、検索ボタンが押されるたびに履歴を更新しています。上記のサンプルでは、4個まで履歴を保存し、それ以上は古いものから消されます。履歴にある文字列が再度検索された場合は、それを一番上に移動しています。
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/DefaultComboBoxModel.html#insertElementAt-E-int- DefaultComboBoxModel#insertElementAt(...) (Java Platform SE 8)]

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