概要

JComboBoxComboBoxEditorJLayerを設定し、その入力が妥当でない場合はアイコンを表示します。

サンプルコード

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, Kotlin

解説

  • 6文字以上入力すると赤い×アイコンを表示するLayerUIを作成
  • JComboBoxBasicComboBoxEditor#getEditorComponent()をオーバーライドしてエディタコンポーネントをJLayer(上記のLayerUIを使用する)に変更したComboBoxEditorを設定
    • BasicComboBoxEditor#createEditorComponent()をオーバーライドすることでエディタのJTextFieldJLayerをする場合は、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);
        }
      }
    });
  }
};

参考リンク

コメント