我正在研究可编辑JComboBox的各种输入验证方式。目前,我需要限制输入为指定范围内的数字。到目前为止,我找到了3种不同的方法。您对最佳方法有什么想法?
JComboBox comboBox = new JComboBox(
new Object[] {"Donnie", "Danny", "Joey", "Jordan", "Jonathan"}
);
comboBox.setEditable(true);
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())
Replace the JTextField of JComboBox by JFormattedTextField.
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) {} }