• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTextField

 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 147
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jennifer,
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");

Notes:
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};
yourDoc.setLegalChars(ints);
// You could set maxLength to 5 for ZIP codes.
yourDoc.setMaxLength(5);
// Add the document to your textfield
yourTextField.setDocument(yourDoc);

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic