如何限制JComboBox中的可编辑文本? [英] How to limit the editable text in JComboBox?

查看:93
本文介绍了如何限制JComboBox中的可编辑文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jcombobox中已经有这个了

I already have this in my jcombobox:

myjcombobox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!(Character.isDigit(c)
                    || (c == KeyEvent.VK_BACK_SPACE)
                    || (c == KeyEvent.VK_DELETE))) {
                getToolkit().beep();
                e.consume();
            }
        }
    });

此代码可防止在jcombobox中写入除数字之外的任何字符.仅数字.但是因为我的jcombobox是可编辑的,所以用户可以写几个数字,这就是问题所在,我想将最大长度设置为4个数字,但不知道我该怎么做....

This code prevents the writing of any character in the jcombobox besides digits. ONLY DIGITS. But since my jcombobox is editable the user can write several digits and that's the problem, i want to set a maximum length of 4 digits but don't know how can i do this....

预先感谢

推荐答案

假设您的JCombobox是最终版本,则可以尝试以下操作:

assuming your JCombobox is final, you can try this:

myjcombobox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (myjcombobox.getEditor().getItem().toString().length() < 4) {
                    if (!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
                        f.getToolkit().beep();
                        e.consume();
                    }
                } else { 
                    e.consume();
                }
            }
        });

这篇关于如何限制JComboBox中的可编辑文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆