Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

validate JTextField - different scenarios?

 
Robert Benson
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm working my way through the scjd book (AM & TC).

I want to validate a JTextField as 8 digits. The PositiveInteger class (using extends PlainDocument) example does nearly what I want and I have tweaked a version to stop checking when 8 digits entered.

However, if you back up and remove a few digits and then start adding more in the middle. The starting offset is not what I was hoping it would be, because of this it goes past 8 digits. It appears to be giving the offset starting from the point of new digits being entered and not the start of the field. Is there a work around for this?

public void insertString(int offs, String str, AttributeSet a)

From looking ar previous posts there are many ways to do this but the one I will use will be one of the following 3:

1 MaskFormatter will functionally provide what I am looking for and is the easiest to implement. But it's cheap and cheerful.
2 extends PlainDocument : I like the feel of the way the PositiveInteger works. Should I keep tweaking until I nail down the offset or will it not do what I am looking for?
3 DocumentListener: have'nt fully explored yet.


Regards, Robert

 
Roel De Nijs
Sheriff
Posts: 10216
129
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Robert,

I also doubted between all the alternatives to block invalid input, started a thread in the swing-forum here. So used the DocumentFilter.
For the assignment I created 2 filters: one allowing a maximum number of chars, the other one allowing a maximum number of digits. The last one I used for the customer id.

Kind regards,
Roel
 
Daniel Breitner
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

my approach was to use a JOptionPane together with the String.matches() method.

Works perfect and is a real simple solution
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic