Limiting the length of text entered in a JTextField

Create a custom component that extends from JTextField and allow the user to specify a maximum length. The implementation is simple: capture the insertString method and execute super.insertString when the condition (current length < = maximumlength) is met.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      getContentPane().add(new LimitedTextField("Try typing more", 15, 15));
      getContentPane().add(new LimitedTextField(10, 3));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class LimitedTextField extends JTextField
{
   private int maxCols = 0;
 
   public LimitedTextField(int maxCols) {
      super();
      this.maxCols = maxCols;
   }
 
   public LimitedTextField(int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
   }
  
   public LimitedTextField(String text, int maxCols) {
      super();
      this.maxCols = maxCols;
      setText(text);
   } 
 
   public LimitedTextField(String text, int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
      setText(text);
   }
 
   protected Document createDefaultModel() {
      return new LimitedDocument();
   }
  
   protected class LimitedDocument extends PlainDocument {
      public void insertString(int offset, String str, AttributeSet as) 
            throws BadLocationException  {
         if (str == null || getLength() + str.length() <= maxCols) {
            super.insertString(offset, str, as);
         }
         else {
            int remainder = maxCols – getLength();
            if (remainder > 0) {
               super.insertString(offset, str.substring(0, remainder), as);
            }
         }
      }
   }
}

Detecting that the mouse enters my JTextField component

Implement a mouseListener and override the methods mouseEntered and mouseExited.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      JTextField textfield = new JTextField(20);
      getContentPane().add(textfield);
      final JLabel label = new JLabel();
      getContentPane().add(label);
 
      textfield.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent me) {
            label.setText("Mouse is inside JTextField!");
         }
         public void mouseExited(MouseEvent me) {
            label.setText("");
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

Enabling a component depending on the text entered in a JTextField

Add a document listener to the JTextField and listen to the characters that are inserted and removed.

Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements DocumentListener
{
   private JTextField tf; 
   private JButton button;
 
   public Main() {           
      getContentPane().setLayout(new BorderLayout());
      JPanel northPanel = new JPanel(new GridLayout(1, 2));
      northPanel.add(new JLabel("Enter an integer: "));
      tf = new JTextField();
      northPanel.add(tf);
      getContentPane().add(BorderLayout.NORTH, northPanel);
      button = new JButton("OK"); 
      getContentPane().add(BorderLayout.SOUTH, button);
      // Add a document listener to the textfield
      Document document = tf.getDocument();
      document.addDocumentListener(this);
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(1);
         }
      });
      button.setEnabled(false);
 
      pack();
   }
 
   public void insertUpdate(DocumentEvent evt) {
      String s = tf.getText();
 
      try {
         int v = Integer.parseInt(s);
         button.setEnabled(true);
      }
      catch(NumberFormatException e) {
         button.setEnabled(false);
      }
   }
 
   public void removeUpdate(DocumentEvent evt) {
      if (tf.getText().length() == 0) {
         button.setEnabled(false);
      }
      else {
         insertUpdate(evt);
      }
   }
 
   public void changedUpdate(DocumentEvent evt) {
   }
 
   public static void main(String args[]) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Automatically transferring the focus when a JTextField column limit has been reached

You can do so by extending JTextField to catch every insertion and checking whether the limit has been reached. If so, you can use transferFocus to have the focus jumpt to the next component.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      getContentPane().add(new AutoFocusTextField("Try typing more", 15, 20));
      getContentPane().add(new AutoFocusTextField(10, 3));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class AutoFocusTextField extends JTextField
{
   private int maxCols = 0;
 
   public AutoFocusTextField(int maxCols) {
      super();
      this.maxCols = maxCols;
   }
 
   public AutoFocusTextField(int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
   }
  
   public AutoFocusTextField(String text, int maxCols) {
      super();
      this.maxCols = maxCols;
      setText(text);
   } 
 
   public AutoFocusTextField(String text, int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
      setText(text);
   }
 
   protected Document createDefaultModel() {
      return new AutoFocusDocument();
   }
  
   protected class AutoFocusDocument extends PlainDocument {
      public void insertString(int offset, String str, AttributeSet as) 
            throws BadLocationException  {
         if (str == null || getLength() + str.length() <= maxCols) {
            super.insertString(offset, str, as);
            if (offset == maxCols-1) {
               transferFocus();
            }
         }
         else {
            int remainder = maxCols - getLength();
            if (remainder > 0) {
               super.insertString(offset, str.substring(0, remainder), as);
            }
            transferFocus();
         }
      }
   }
}

Creating a JFormattedTextField that only accepts telephone numbers

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JFormattedTextField formattedTf =
                   new JFormattedTextField(new MaskFormatter("(###) ###-####"));
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Creating a JFormattedTextField that only accepts SSNs

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JFormattedTextField formattedTf =
                   new JFormattedTextField(new MaskFormatter("###-##-####"));
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Catching the Enter key event on a JTextField

The following example shows a JDialog with one JTextField. When the Enter key is detected, it will perform a doClick on the OK button.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JDialog
{
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 1, 20, 20)); 
      final JTextField inputField = new JTextField();
      getContentPane().add(inputField);
 
      final JButton okButton = new JButton("Ok");
      JButton cancelButton = new JButton("Cancel");
      JPanel panel = new JPanel(new GridLayout(1, 2));
      panel.add(okButton);
      panel.add(cancelButton);
 
      getContentPane().add(panel);     
        
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Ok pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Cancel pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // catch the enter key in the JTextField and perform an OK click on the JButton
      inputField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_ENTER) {
               okButton.doClick();
            }
         }
      });
 
      pack();
      centerDialog();
   }
 
   public void centerDialog() {
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      int x = (int) ((d.getWidth() - getWidth()) / 2);
      int y = (int) ((d.getHeight() - getHeight()) / 2);
      setLocation(x, y);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

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.

Main.java:

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) {
            System.exit(0);
         }
      });
 
      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"));
      getContentPane().add(BorderLayout.CENTER, 
                               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);
      main.setVisible(true);
   }
}
 
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 " + 
                               pattern.pattern());      
         return m.matches();
      }        
      return true;     
   }
 
   public boolean shouldYieldFocus(JComponent input) {
      return verify(input);
   }
}

Setting the selected file in a the filename textfield JFileChooser when it starts up

You just have to create a new File and set it as selectedFile before starting the FileChooser. Depending on what you want to do with the selected file you should check the file with File.canRead(), File.canWrite() or File.exists(). Here is an example:

File file = new File(date + " " + user + ".pdf");
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(file);
int returnValue = fc.showSaveDialog(this);

This must be wrapped in a try-catch-block, because creating a File could throw an exception.