【问题标题】:Java - Editable ComboBox ValidationJava - 可编辑组合框验证
【发布时间】:2009-05-01 19:21:22
【问题描述】:

我正在研究验证可编辑 JComboBox 输入的各种方法。目前,我需要将输入限制为指定范围内的数字。到目前为止,我已经找到了 3 种不同的方法。对解决此问题的最佳方法有何想法?

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

comboBox.setEditable(true);
  1. 通过实现覆盖方法 insertString 和 remove 的专用 Document 来控制用户输入。

    // get the combo boxes editor component
    JTextComponent editor =
            (JTextComponent) comboBox.getEditor().getEditorComponent();
    // change the editor's document
    editor.setDocument(new BadDocument())
    
  2. 将JComboBox的JTextField替换为JFormattedTextField。

  3. 您可以使用输入验证器来替代自定义格式化程序

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

谢谢。

【问题讨论】:

    标签: java validation jcombobox


    【解决方案1】:

    这就是 InputVerifier 的设计目的。我会从其中一个开始,但实际上这应该可以解决问题。您的要求中有什么特殊原因说明它为什么不起作用?

    【讨论】:

    • 没有理由。刚刚注意到大量选项,并希望更好地了解当前的最佳做法。
    • 再考虑一下,我实际上想防止输入除数字之外的任何内容。 InputVerifier 仅在失去焦点之前进行检查。输入每个字符时如何检查?谢谢。
    • 好的,如果您需要“实时”,我会选择自定义文档方法
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多