Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I set an inputmask on a JTextfield?

Status
Not open for further replies.

Themuppeteer

Programmer
Apr 4, 2001
449
0
0
BE
I have an input field that takes a ip address.
I would like that the user can only give in numbers and that the "." are already filled in. So that nothing can go wrong with the input.
I have searched the net but the classes that are used there
do not seem to be in my jbuilder (like MaskFormatter etc.).
Can ny1 give me a solution ?
thnx. Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
Hi Themuppeteer,

I think what you're going to want to use here is a custom document that will get attached to your text field. I've done this before for a date input field, and although it's kind of tricky, it's definitely do-able.

Create an IPDocument that extends PlainDocument. You'll want to overload the insertString() method of the PlainDocument class, adding the logic for the IP address String entry. There are two key methods of the PlainDocument class that you'll be interested in.. namely, remove(), and insertString().

In your IPDocument's insertString() method, you can examine the String that is typed, modify it, and then append the desired String to the document (i.e. the text in the text box). So for example, in the DateDocument that I created, I examined the String typed in, and if it was numeric and was at position 1 or 4, I would append the String itself plus a "/" character, to enforce the standard format. You would obviously do something very similar with a "." instead of a "/".

Finally, after your custom document class has been created, you create an instance of it and pass the instance to the setDocument() method of your text field instance.

This is one way of dealing with this problem. I'm sure there are other approaches, but this one seemed to work nicely for me. If anyone else has other suggestions, I personally would love to hear them.

Hope this helps,
Adam Rice
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top