File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Regex constraint on a textfield Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regex constraint on a textfield" Watch "Regex constraint on a textfield" New topic

Regex constraint on a textfield

Jess Dancel

Joined: Nov 07, 2007
Posts: 11
Hello, all.

I want to put a constraint on a JFormattedTextField that will only allow characters matching a regex to be entered (in this case, only hex digits 0-E).

The possible solutions I've found to this are all quite complicated. I know I've done it before and it was simple, but having trouble remembering.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 32818

Welcome to JavaRanch!

This character class matches hex: [0-9A-E]

What else are you looking for that was complicated?

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Jessica Dancel

Joined: Dec 07, 2006
Posts: 10
I was wondering how to add that as a constraint to a textfield, so that the user can only enter those characters.
Hiroshi Iwatani

Joined: Jan 15, 2008
Posts: 3
Use MaskFormatter. See the doc of the class for its usage.
Jess Dancel

Joined: Nov 07, 2007
Posts: 11
Thank you, Hiroshi! MaskFormatter did exactly what I needed.
I agree. Here's the link:
subject: Regex constraint on a textfield
It's not a secret anymore!