Validating a textfield using the regex package

You can use a custom InputVerifier in which you try to match the desired regular expression for that textfield.

import java.util.regex.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class Main extends JFrame
   public Main() {
      super("JFormattedTextField REGEX example");
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
      getContentPane().setLayout(new BorderLayout());
      JFormattedTextField ftf = new JFormattedTextField();
      getContentPane().add(BorderLayout.NORTH, ftf);
      ftf.setInputVerifier(new RegExFieldVerifier("[abcd]+"));
      getContentPane().add(BorderLayout.SOUTH, new JTextField("Normal textfield"));
                               new JLabel("<HTML>REGEX USED:  [abcd]+   allowed: " +
                                          "one or more of the following characters: " +
                                          "a,b,c or d.<BR>Use the TAB key to switch!</HTML>"));
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.setSize(300, 300);
class RegExFieldVerifier extends InputVerifier {
   Pattern pattern;
   public RegExFieldVerifier(String regex) {
      pattern = Pattern.compile(regex);
   public boolean verify(JComponent input) {
      if (input instanceof JFormattedTextField) {
         JFormattedTextField ftf = (JFormattedTextField)input;
         String line = ftf.getText();
         Matcher m = pattern.matcher(line);
         if (!m.matches()) 
            System.out.println("Doesn't match regular expression " + 
         return m.matches();
      return true;     
   public boolean shouldYieldFocus(JComponent input) {
      return verify(input);