Question

I'm looking into the various ways to validate input for an editable JComboBox. Currently, I need to restrict input to numbers in a specified range. Thus far I've found 3 distinct ways. Any thoughts on the best way to approach this?

JComboBox comboBox = new JComboBox(
    new Object[] {"Donnie", "Danny", "Joey", "Jordan", "Jonathan"}
);

comboBox.setEditable(true);
  1. Get control over the user input by implementing a specialized Document overriding the methods insertString and remove.

    // get the combo boxes editor component
    JTextComponent editor =
            (JTextComponent) comboBox.getEditor().getEditorComponent();
    // change the editor's document
    editor.setDocument(new BadDocument())
    
  2. Replace the JTextField of JComboBox by JFormattedTextField.

  3. You can use an input verifier as an alternative to a custom formatter

    // set the input verifier
    setInputVerifier(verifier);
    
    class MyVerifier extends InputVerifier implements ActionListener 
    {
        public boolean shouldYieldFocus(JComponent input) {}
    }
    

Thanks.

Was it helpful?

Solution

This is what the InputVerifier was designed to do. I'd start with one of them, but really that should do the trick. Any particular reason in your requirements as to why it would not work?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top