ComboBoxEditorにJLayerを設定し入力の妥当性を表示する
Total: 4084, Today: 2, Yesterday: 1
Posted by aterai at
Last-modified:
Summary
JComboBoxのComboBoxEditorにJLayerを設定し、その入力が妥当でない場合はアイコンを表示します。
Screenshot

Advertisement
Source Code Examples
comboBox.setEditable(true);
comboBox.setInputVerifier(new LengthInputVerifier());
comboBox.setEditor(new BasicComboBoxEditor() {
private Component editorVerifier;
@Override public Component getEditorComponent() {
if (editorVerifier == null) {
JTextComponent tc = (JTextComponent) super.getEditorComponent();
editorVerifier = new JLayer<JTextComponent>(tc, new ValidationLayerUI());
}
return editorVerifier;
}
});
View in GitHub: Java, KotlinDescription
6文字以上入力すると赤い×アイコンを表示するLayerUIを作成- アイコンはHow to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With Swing > Using Other Swing Features)から引用
- 入力の妥当性の検証自体は
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);
}
}
});
}
};
Reference
JLayerを使用したコンポーネントのデコレート方法- How to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With Swing > Using Other Swing Features)