File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Mask JTextField  1.3 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Mask JTextField  1.3" Watch "Mask JTextField  1.3" New topic
Author

Mask JTextField 1.3

Rodolfo Velasco
Greenhorn

Joined: Jul 05, 2006
Posts: 17
Hi Ranchers ...

it is possible to Mask a JTextField in JDK 1.3 ?

I'm trying to make it easyer for the user to enter a date and a Phone number

Like (XXX)XXX-XXXX
oR XX/XX/XXXX

Thanks in Advance ...
Brian Mozhdehi
Ranch Hand

Joined: Aug 17, 2006
Posts: 81
You can do one of two things that I know of off the top of my head. One is use a keylistener on the textfield and in your method KeyReleased, validate the last character pressed to see if its consistent with the mask, i.e. if the mask is (XXX) XXX-XXXX, then when they enter the 10th character, make sure its a "-" or enter the dash for them. How you know what character they are on is YourTextField.getText().trim().length() (after checking that getText() is not null).

Something like this:

public void keyReleased(KeyEvent e)
{
String data = "";

if(YourTextField.getText() != null)
data = YourTextField.getText().trim();

int index = data.length();

if(index = 1 && e.getKeyChar() != ')')
//show error message and return
else if(index = 2 && Character.isDigit(e.getKeyChar())
//show error message and return

//etc, etc
}

The other way is to validate on focusLost, i.e. using a focus listener, which doesnt really validate as they enter, but at least validates before they save.
 
 
subject: Mask JTextField 1.3