Swing/ComboBoxEditorVerifier のバックアップ(No.2)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/ComboBoxEditorVerifier へ行く。
- 1 (2015-11-02 (月) 00:55:30)
- 2 (2015-11-02 (月) 16:48:55)
- 3 (2016-03-31 (木) 17:38:24)
- 4 (2016-06-12 (日) 00:24:24)
- 5 (2017-09-16 (土) 14:59:22)
- 6 (2018-02-24 (土) 19:51:30)
- 7 (2019-03-01 (金) 16:14:25)
- 8 (2020-12-18 (金) 16:02:55)
- 9 (2023-05-26 (金) 18:52:48)
- 10 (2025-01-03 (金) 08:57:02)
- 11 (2025-01-03 (金) 09:01:23)
- 12 (2025-01-03 (金) 09:02:38)
- 13 (2025-01-03 (金) 09:03:21)
- 14 (2025-01-03 (金) 09:04:02)
- title: ComboBoxEditorにJLayerを設定し入力の妥当性を表示する tags: [JComboBox, ComboBoxEditor, JLayer, InputVerifier] author: aterai pubdate: 2015-11-02T00:47:14+09:00 description: JComboBoxのComboBoxEditorにJLayerを設定し、その入力が妥当でない場合はアイコンを表示します。
概要
JComboBox
のComboBoxEditor
にJLayer
を設定し、その入力が妥当でない場合はアイコンを表示します。
Screenshot

Advertisement
サンプルコード
comboBox.setEditable(true);
comboBox.setInputVerifier(new LengthInputVerifier());
comboBox.setEditor(new BasicComboBoxEditor() {
private Component editorComponent;
@Override public Component getEditorComponent() {
if (editorComponent == null) {
JTextComponent tc = (JTextComponent) super.getEditorComponent();
editorComponent = new JLayer<JTextComponent>(tc, new ValidationLayerUI());
}
return editorComponent;
}
});
View in GitHub: Java, Kotlin解説
6
文字以上入力すると×アイコンを表示するLayerUI
を作成- アイコンはJLayerを使用したコンポーネントのデコレート方法から引用
- 入力の妥当性の検証自体は、
JComboBox
に設定したInputVerifier
を使用
JComboBox
にBasicComboBoxEditor#getEditorComponent()
をオーバーライドしてエディターコンポーネントをJLayer
(上記のLayerUI
を使用する)に変更したComboBoxEditor
を設定BasicComboBoxEditor#createEditorComponent()
をオーバーライドすることでエディタのJTextField
にJLayer
をする場合は、BasicComboBoxEditor#getItem()
などのメソッドも修正するf.setName("ComboBox.textField");
とエディターに名前を設定しておくと、NimbusLookAndFeel
などでフォーカス時のBorder
が正しく描画される
- Enterキーで
JComboBox
に編集中の文字列をアイテム追加する場合もInputVerifier
で検証するように設定
JComboBox<String> comboBox = new JComboBox<String>(model) {
@Override public void updateUI() {
super.updateUI();
final JComboBox<String> cb = this;
getActionMap().put("enterPressed", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
if (getInputVerifier().verify(cb)) {
String str = Objects.toString(getEditor().getItem(), "");
DefaultComboBoxModel<String> m =
(DefaultComboBoxModel<String>) getModel();
m.removeElement(str);
m.insertElementAt(str, 0);
if (m.getSize() > 10) {
m.removeElementAt(10);
}
setSelectedIndex(0);
}
}
});
}
};