How to limit the input length of JTextArea using events?Is it possible?
Printable View
How to limit the input length of JTextArea using events?Is it possible?
Have a look at the addInputMethodListener method to see if you can add an input listener and every time an event comes in you will have to check the text in the textarea and cut it if its too long.
JTextComponent (Java Platform SE 6))
// Json
I tried with InputMethodTextChanged() action.But it didn't provide any feasible solution.Also with
private void tfBannerKeyTyped(java.awt.event.KeyEvent evt) {
if(tfBanner.getText().length() > 10)
evt.consume();
}
here, we couldn't enter any text.But can to copy and paste.I don't want to do that.Please provide some other possible solution please.
I'm not sure how you create your JTextArea, but after some googling this is what I found.
http://java.sun.com/docs/books/tutor...izeFilter.java
You need to do something like this.
Code :final PlainDocument plainDocument = new PlainDocument(); plainDocument.setDocumentFilter(new DocumentSizeFilter(10)); final JTextArea textArea = new JTextArea(plainDocument);
Add this class where appropriate.
Code :private static class DocumentSizeFilter extends DocumentFilter { int maxCharacters; public DocumentSizeFilter(int maxChars) { maxCharacters = maxChars; } public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { System.out.println("in DocumentSizeFilter's insertString method"); if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) super.insertString(fb, offs, str, a); else Toolkit.getDefaultToolkit().beep(); } public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException { System.out.println("in DocumentSizeFilter's replace method"); if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) super.replace(fb, offs, length, str, a); else Toolkit.getDefaultToolkit().beep(); } }
// Json
Thanks Json.Its working.
final PlainDocument plainDocument = new PlainDocument();
plainDocument.setDocumentFilter(new DocumentSizeFilter(10));
final JTextArea textArea = new JTextArea(plainDocument); - Instead of this i use the coding,
PlainDocument pDoc=(PlainDocument)tfBanner.getDocument();
pDoc.setDocumentFilter(new DocumentSizeFilter(10));
Its working exactly what i want.Thanks a lot.