Omar Enrique Otero
Omar Enrique Otero

Reputation: 23

How to limit the editable text in 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();
            }
        }
    });

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

Upvotes: 2

Views: 2300

Answers (2)

Mordechai
Mordechai

Reputation: 16234

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

Upvotes: 1

Martin Seeler
Martin Seeler

Reputation: 6982

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

Upvotes: 1

Related Questions