Enforce max characters on Swing JTextArea with a few curve balls

前端 未结 3 841
南笙
南笙 2021-01-16 04:48

I\'m trying to add functionality to a Swing JLabel and JTextArea such that:

  • The user is only allowed to enter 500 characters into the textarea (max)
  • T
3条回答
  •  旧巷少年郎
    2021-01-16 05:34

    To add on to what Ray S. Kan said:

    There is an easier way to limit the characters for a JTextArea without having to use a DocumentFilter as shown by Ray S. Kan, but the issue with his answer is that it does not prevent someone from pasting in a long text. The following will prevent a user from pasting in stuff to bypass the limit:

    @Override
    public void keyTyped(KeyEvent e) {
        int max = 25;
        if(text.getText().length() > max+1) {
            e.consume();
            String shortened = text.getText().substring(0, max);
            text.setText(shortened);
        }else if(text.getText().length() > max) {
            e.consume();
        }
    }
    

    This will stop a key from being pressed if the length is not pass max, but if it passes max, it will simply replace the string in the text area with a shorter string. The text variable is the JTextArea swing object.

提交回复
热议问题