Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mask JTextField 1.3

 
Rodolfo Velasco
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic