my dog learned polymorphism
The moose likes Swing / AWT / SWT and the fly likes JTextField Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTextField" Watch "JTextField" New topic


Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Hi. Still kinda new at this stuff, so bear with me. How do I allow only numeric characters to be keyed into a JTextField?
I have an application updating a file on the AS/400, but if the field is numeric (such as zip code) and the user does not key anything in it, it outputs blanks for the zip code field in that file.
If I could make my JTextField to only allow numerics, will it automatically put zeros out instead of blanks?
If not, how do I get the zeros in my file??
Please Help!
Thanks in advance!
Glen Tanner
Ranch Hand

Joined: Apr 16, 1999
Posts: 147

Here's a code snippet that I hope will help you out with your problem with text field masks.
I'm not sure how you want to handle storing 0's if nothing is entered. Perhaps you could initially set the text field with 5 zeros??
JTextField yourTextField = new JTextField("00000");

import javax.swing.text.PlainDocument;
//Create the document:
NumberDocument yourDoc = new NumberDocument();

// Create the "legal" chars for your text fields.
char[] ints = {1,2,3,4,5,6,7,8,9,0};
// You could set maxLength to 5 for ZIP codes.
// Add the document to your textfield

jQuery in Action, 3rd edition
subject: JTextField
It's not a secret anymore!