How to limit the editable text in JComboBox?

蹲街弑〆低调 提交于 2019-12-11 00:06:42

问题


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();
            }
        }
    });

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....

Thanks in advance


回答1:


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();
                }
            }
        });



回答2:


Set your own Document to the component (assuming it's a JTextField):

.setModel(new PlainDocument(){

    public void insertString(int offset, String text, AttributeSet attr){
        if(getLength() + text.length() > 4){
            Toolkit.getToolkit.beep();
            return;
        }

        for(char c : text.toCharArray(){
            if(!Character.isDigit(c){
                || (c != KeyEvent.VK_BACK_SPACE)
                || (c != KeyEvent.VK_DELETE)){

                Toolkit.getToolkit.beep();
                return;
            } 

        }
        super.insertString(offset,text,attr);
    }
}); 


来源:https://stackoverflow.com/questions/13649587/how-to-limit-the-editable-text-in-jcombobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!