What are the differences between a JTextField and a JFormattedTextField in Java?



In Java, a JTextField can be used for plain text, whereas a JFormattedTextField is a class that extends JTextField, and it can be used to set any format to the text that it contains, phone numbers, e-mails, dates, etc.

JTextField

A JTextField is one of the most important components that allows the user to type an input text value in a single-line format. A JTextField can also generate the MouseListener and KeyListener interfaces.

Syntax

The following is the syntax for a JTextField initialization:

JTextField textField = new JTextField(20); // 20 columns wide

A JTextField can generate an ActionListener interface when we try to enter some input inside the text field, and it can generate a CaretListener interface each time the caret (i.e., the cursor) changes position.

Methods of JTextField

The following are some common methods in JTextField:

getText():

The getText() method retrieves the text entered in the field.

Method Declaration:

public String getText()

selectAll():

The selectAll() method selects all the text in the field.

Method Declaration:

public void selectAll()

getDocument():

The getDocument() method returns the underlying Document object, which allows for more advanced text manipulation.

Method Declaration:

public Document getDocument()

Common Use Cases for JTextField

The following are some common use cases for JTextField in Java:

  • When we need to add simple text input (names, comments, search boxes).
  • When there is no need for validation or formatting.

Example of JTextField

Below is an example of a JTextField on a Swing GUI in Java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldTest extends JFrame {
   JTextField jtf;
   public JTextFieldTest() {
      setTitle("JTextField Test");
      setLayout(new FlowLayout());
      jtf = new JTextField(15);
      add(jtf);
      jtf.addActionListener(new ActionListener() {
         public void actionPerformed (ActionEvent ae) {
            System.out.println("Event generated: " + jtf.getText());
         }
      });
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JTextFieldTest();
   }
}

Output

JFormattedTextField

A formatted text field is an instance of the class JFormattedTextField, which is a direct subclass of JTextField. A JFormattedTextField is like a normal text field except that it controls the validity of the characters the user types, and it can be associated with a formatter that specifies the characters the user can enter.

Syntax

The following is the syntax for a JFormattedTextField initialization:

MaskFormatter phoneFormatter = new MaskFormatter("(###) ###-####");
phoneFormatter.setPlaceholderCharacter('_');

JFormattedTextField phoneField = new JFormattedTextField(phoneFormatter);
phoneField.setColumns(15);

A JFormattedTextField is a subclass of the Format class to build a formatted text field. We can create a formatter, customize it if necessary. We can call the JFormattedTextField(Format format) constructor, which takes an argument of type Format.

Methods in JFormattedTextField

The following are some common methods in JFormattedTextField:

getFormatter():

The getFormatter() method returns the current Formatter associated with the field.

Method Declaration:

public JFormattedTextField.AbstractFormatter getFormatter()

setValue():

The setValue() method sets the value of the field, automatically formatting it based on the Formatter.

Method Declaration:

public void setValue(Object value)

getValue():

The getValue() method returns the value of the field, potentially as a formatted object (e.g., a Number or Date).

Method Declaration:

public Object getValue()

Common Use Cases for JFormattedTextField

The following are some common use cases for JFormattedTextField in Java:

  • When structured data input is required(dates, numbers, currencies).
  • When there is a need for validation (e.g., correct date format).
  • For masked input like credit cards, phone numbers.

Example of JFormattedTextField

Below is an example of a JFormattedTextField on a Swing GUI in Java:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JFormattedTextFieldTest extends JFrame {
   JFormattedTextField jftf;
   MaskFormatter mf;
   public JFormattedTextFieldTest() {
      setTitle("JFormattedTextField Test");
      setLayout(new FlowLayout());
      // A phone number formatter - (country code)-(area code)-(number)
      try {
         mf = new MaskFormatter("##-###-#######");
         mf.setPlaceholderCharacter('#');
         jftf = new JFormattedTextField(mf);
         jftf.setColumns(12);
      } catch(Exception e) {
         e.printStackTrace();
      }
      add(jftf);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JFormattedTextFieldTest();
   }
}

Output

Difference Table

The following are some key differences between a JTextField and a JFormattedTextField in Java:

Criteria JTextField JFormattedTextField
Input Type Plain text Formatted text (numbers, dates, etc.)
Formatting None Supports formatting through Formatter
Validation Basic (e.g., character limit) Advanced validation based on format
Data Binding Not directly supported Supports data binding through Formatter
Error Handling Limited Provides visual cues and error messages
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-04-23T17:18:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements