limit characters in textfield in swing
I am designing a calculator in which user enters the numbers by clicking a mouse button.
The problem is it takes endless characters and i want to limit the number of input characters to 10.
I tried using "setColumns(10)" to textfield but it does not solve the problem .
Can anyone show me the way to limit number of characters.
Re: limit characters in textfield in swing
one way is to use a FormattedTextField. Myself I kind of like using a DocumentFilter as it is quite flexible.
Re: limit characters in textfield in swing
Use Document Listener to your text field.. then override "public void insertUpdate(DocumentEvent E)" method..
in that You will Place Your Condition as textField.getDocument().getLength() is not more than 10.. if entered more than ten U will display any Message Box.. I think it will work for You.
Re: limit characters in textfield in swing
Quote:
Originally Posted by
ch.nagaraju111
Use Document Listener to your text field.. then override "public void insertUpdate(DocumentEvent E)" method..
in that You will Place Your Condition as textField.getDocument().getLength() is not more than 10.. if entered more than ten U will display any Message Box.. I think it will work for You.
No, this is the wrong way to go as it checks the text after it has been added to the textcompoment. Again, much better is to use a DocumentFilter which checks the text before it is added to the component, and so you can delete it, improve it, or otherwise modify it before adding it to the component. The filter is definitely the way to go.
Re: limit characters in textfield in swing
Quote:
Originally Posted by
Fubarable
No, this is the wrong way to go as it checks the text after it has been added to the textcompoment. Again, much better is to use a DocumentFilter which checks the text before it is added to the component, and so you can delete it, improve it, or otherwise modify it before adding it to the component. The filter is definitely the way to go.
thanks.