Google Tag Manager

2016/03/03

Validating input on an editable JComboBox with InputVerifier and JLayer

Code

JComboBox comboBox = new JComboBox(model) {
  @Override public void updateUI() {
    getActionMap().put(ENTER_PRESSED, null);
    super.updateUI();
    final JComboBox cb = this;
    final Action defalutEnterPressedAction = getActionMap().get(ENTER_PRESSED);
    getActionMap().put(ENTER_PRESSED, new AbstractAction() {
      @Override public void actionPerformed(ActionEvent e) {
        boolean isPopupVisible = isPopupVisible();
        setPopupVisible(false);
        DefaultComboBoxModel m = (DefaultComboBoxModel) getModel();
        String str = Objects.toString(getEditor().getItem(), "");
        if (m.getIndexOf(str) < 0 && getInputVerifier().verify(cb)) {
          m.removeElement(str);
          m.insertElementAt(str, 0);
          if (m.getSize() > 10) {
            m.removeElementAt(10);
          }
          setSelectedIndex(0);
          setPopupVisible(isPopupVisible);
        } else {
          defalutEnterPressedAction.actionPerformed(e);
        }
      }
    });
  }
};
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(tc, new ValidationLayerUI());
    }
    return editorComponent;
  }
});

class LengthInputVerifier extends InputVerifier {
  private static final int MAX_LEN = 6;
  @Override public boolean verify(JComponent c) {
    if (c instanceof JComboBox) {
      JComboBox cb = (JComboBox) c;
      String str = Objects.toString(cb.getEditor().getItem(), "");
      return MAX_LEN - str.length() >= 0;
    }
    return false;
  }
}

References

No comments:

Post a Comment