• category: swing folder: ComboBoxEditorVerifier title: ComboBoxEditorにJLayerを設定し入力の妥当性を表示する tags: [JComboBox, ComboBoxEditor, JLayer, InputVerifier] author: aterai pubdate: 2015-11-02T00:47:14+09:00 description: JComboBoxのComboBoxEditorにJLayerを設定し、その入力が妥当でない場合はアイコンを表示します。 image: https://lh3.googleusercontent.com/-4gsRLzrKTE0/VjYu_qwZ8pI/AAAAAAAAOFk/t0JvVmjMcjI/s800-Ic42/ComboBoxEditorVerifier.png hreflang:
       href: https://java-swing-tips.blogspot.com/2016/03/validating-input-on-editable-jcombobox.html
       lang: en

概要

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

サンプルコード

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を作成
  • 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);
        }
      }
    });
  }
};

参考リンク

コメント