Link to home
Start Free TrialLog in
Avatar of bangviz
bangviz

asked on

JTextArea Special Character and limitation

Hi,

Further to advice last week. Can any one assist With the below example

1) how can i avoid special characterlike @%~ from being typed.
2) Secondly If you set limit to 150 characters and try pasting  block of 160 characters it  should only accept the first 150 characters  
    (truncate). This does not happen and it does not accept any block of charcters above 150 characters when pasted.

    JTextComponent textComponent = new JTextField();
    AbstractDocument doc = (AbstractDocument)textComponent.getDocument();
    doc.setDocumentFilter(new FixedSizeFilter(150));
   
    class FixedSizeFilter extends DocumentFilter {
        int maxSize;
   
        // limit is the maximum number of characters allowed.
        public FixedSizeFilter(int limit) {
            maxSize = limit;
        }
   
        // This method is called when characters are inserted into the document
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String str,
                AttributeSet attr) throws BadLocationException {
            replace(fb, offset, 0, str, attr);
        }
   
        // This method is called when characters in the document are replace with other characters
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
                String str, AttributeSet attrs) throws BadLocationException {
            int newLength = fb.getDocument().getLength()-length+str.length();
            if (newLength <= maxSize) {
                fb.replace(offset, length, str, attrs);
            } else {
                throw new BadLocationException("New characters exceeds max size of document", offset);
            }
        }
    }

Thanks
Bangviz
ASKER CERTIFIED SOLUTION
Avatar of mukundha_expert
mukundha_expert

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bangviz
bangviz

ASKER

An example for both cases appreciated thanks
you can check the both in the insertString method of the document filter you have posted!
If you want the user to enter only the alphabets and numbers then you can try something like this in the KeyDown event,

     char ch =' ' ;

     if  ( ( ch >= 'a'  && ch <= 'z' )  || ( ch >='A' && ch <= 'Z' ) || ( ch >= '0' && ch <= '9') )
           return true;


its lot of work or messy in doing it in key event, good to do it in the insertString method of th document or the filter!
and ofcourse to have the code in replace method!