Java - 可编辑组合框验证

3

我正在研究可编辑JComboBox的各种输入验证方式。目前,我需要限制输入为指定范围内的数字。到目前为止,我找到了3种不同的方法。您对最佳方法有什么想法?

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) {}
    }
    
感谢。
1个回答

2

这就是InputVerifier的设计初衷。我建议你使用其中的一个,那应该就能解决问题了。有没有什么特殊原因,不能满足你的需求呢?


没有任何理由,只是注意到有大量的选项,希望更好地了解当前的最佳实践。 - javacavaj
经过更深入的思考,我实际上想防止输入除数字以外的任何内容。InputVerifier仅在失去焦点之前进行检查。我该如何在每输入一个字符时进行检查?谢谢。 - javacavaj
好的,如果你需要“实时”的话,我会选择自定义文档方法。 - willcodejavaforfood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接