• title: ComboBoxEditorにJLayerを設定し入力の妥当性を表示する tags: [JComboBox, ComboBoxEditor, JLayer, InputVerifier] author: aterai pubdate: 2015-11-02T00:47:14+09:00 description: JComboBoxのComboBoxEditorにJLayerを設定し、その入力が妥当でない場合はアイコンを表示します。

概要

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);
        }
      }
    });
  }
};

コメント