*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes validate JTextField - different scenarios? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "validate JTextField - different scenarios?" Watch "validate JTextField - different scenarios?" New topic
Author

validate JTextField - different scenarios?

Robert Benson
Ranch Hand

Joined: Apr 04, 2010
Posts: 56
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


SCJP 6 , OCMJD 6 ,
http://www.robertbenson.ie/
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5126
    
  12

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


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Daniel Breitner
Ranch Hand

Joined: Nov 13, 2008
Posts: 70
Hi,

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

Works perfect and is a real simple solution


Visit me at http://liferay-blogging.blogspot.com
 
 
subject: validate JTextField - different scenarios?
 
Similar Threads
NX: customer ID in urlybird
Data validation
Are there any framework to validate the value of a textfield?
Extending JTextField
JOptionPane/JDialog question