简体   繁体   English

如何让InputVerifier与可编辑的JComboBox一起使用

[英]How do I get InputVerifier to work with an editable JComboBox

I've got an JComboBox with a custom inputVerifyer set to limit MaxLength when it's set to editable. 我有一个JComboBox ,其自定义inputVerifyer设置为在设置为可编辑时限制MaxLength。

The verify method never seems to get called. 验证方法似乎永远不会被调用。
The same verifyer gets invoked on a JTextField fine. JTextField上调用相同的verifyer。

What might I be doing wrong? 我可能做错了什么?

I found a workaround. 我找到了一个解决方法。 I thought I'd let the next person with this problem know about. 我以为我会让下一个有这个问题的人知道。

Basically. 基本上。 Instead of setting the inputVerifier on the ComboBox you set it to it's "Editor Component". 而不是在ComboBox上设置inputVerifier,而是将其设置为“编辑器组件”。

JComboBox combo = new JComboBox();
JTextField tf = (JTextField)(combo.getEditor().getEditorComponent());
tf.setInputVerifier(verifyer);

Show us a small section of your code. 向我们展示您的代码的一小部分。

package inputverifier;

import javax.swing.*;

    class Go {
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
            runEDT();
        }});
    }
    private static void runEDT() {
        new JFrame("combo thing") {{
            setLayout(new java.awt.GridLayout(2, 1));
            add(new JComboBox() {{
                setEditable(true);
                setInputVerifier(new InputVerifier() {
                    @Override public boolean verify(JComponent input) {
                        System.err.println("Hi!");
                        return true;
                    }
                });
            }});
            add(new JTextField());
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }};
    }    
}

Looks like it's a problem with JComboBox being a composite component. 看起来JComboBox是一个复合组件是一个问题。 I'd suggest avoiding such nasty UI solutions. 我建议避免这种令人讨厌的UI解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM