views:

911

answers:

1

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.

+1  A: 

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?

willcodejavaforfood
no reason. just noted the large number of options and wanted to better understand what is the current best practice.
javacavaj
Giving this a bit more thought I would actually like to prevent entry of anything but numbers. The InputVerifier checks only before losing focus. How can I check as each character is entered? Thanks.
javacavaj
OK then I'd go for the custom Document approach if you need it 'live'
willcodejavaforfood