I\'m trying to add functionality to a Swing JLabel and JTextArea such that:
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.