• Post Reply Bookmark Topic Watch Topic
  • New Topic

JTextField: How to limit the number of characters?

 
Darya Akbari
Ranch Hand
Posts: 1855
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to limit the number of characters (digits) in a JTextField?

Regards,
Darya
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it is for digits, use a JFormattedTextField with a NumberFormat instance. e.g:

This will limit the input to the form nnn.nn.
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Implementing a Document Filter on the Text Component Features page of the tutorial.
 
Darya Akbari
Ranch Hand
Posts: 1855
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your responses.

But I need the JTextField as an input text field with maximum size of 8 digits.

I don't like the Document Filter because it's too complicate. Since I use JDK 1.4.2 I want some new approach.

Any hints?

Regards,
Darya
 
Lionel Badiou
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Darya,

Maybe you could use JSpinner(ready-to-use component to ensure digit inputs with "legal" values).

Hope that helps,
 
Darya Akbari
Ranch Hand
Posts: 1855
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lionel,

thanks for the info. Honestly I've never heard about the JSpinner . But that's all too complicate.

I'll stay with a simple solution and check the input String length and throw a Message as shown below:



Thanks for your answers.

Regards,
Darya
 
Lionel Badiou
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Darya,

Feel free to choose the solution that suits your needs. Be careful yet, your code does not guarantee that user enters only digits. So, you need one more check and consequently one more error message. This is the kind of things that JSpinner manages automatically. The use of JSpinner is as simple as calling a contructor but actually, this component is suitable mainly for small numbers (like page number).

Best regards,
 
Darya Akbari
Ranch Hand
Posts: 1855
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lionel,

thanks again for your answer. In my case it's also acceptable when the user enters a alpha-numerical value, which is not correct but as my SCJD assignment says:


The system you are writing does not interact with these numbers, rather it simply records them.


So the user is responsible to input the right number.

But beside of my SCJD assignment and if it's not too much :roll: please send a solution how you would replace my code snippet with JSpinner.

Regards,
Darya
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!