JFormattedTextField

 

✅ Java Swing JFormattedTextField – Overview & Usage

JFormattedTextField is a Swing component that restricts input to a specific format such as numbers, dates, currency, phone numbers, etc.


🔧 Key Features

Feature Description
setValue(Object) Set initial/formatted value
getValue() Get current formatted value
setFormatterFactory(...) Set a custom formatter like number, date, etc.
Supports masks Input masks (e.g., for phone numbers)
Formatting on focus lost Value becomes formatted when user leaves the field

✅ Common Use Cases with Examples

1. Number Format

import javax.swing.*;
import java.text.NumberFormat;

public class NumberFormattedField {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Number Format");
        frame.setSize(300, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        JFormattedTextField numberField = new JFormattedTextField(numberFormat);
        numberField.setValue(1234.56);  // default value

        frame.add(numberField);
        frame.setVisible(true);
    }
}

2. Date Format

import javax.swing.*;
import java.text.DateFormat;

public class DateFormattedField {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Date Format");
        frame.setSize(300, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
        JFormattedTextField dateField = new JFormattedTextField(dateFormat);
        dateField.setValue(new java.util.Date());

        frame.add(dateField);
        frame.setVisible(true);
    }
}

3. Mask Formatter (Phone Number)

import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.text.ParseException;

public class MaskFormatField {
    public static void main(String[] args) throws ParseException {
        JFrame frame = new JFrame("Phone Number");
        frame.setSize(300, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MaskFormatter phoneFormat = new MaskFormatter("(###)-###-####");
        JFormattedTextField phoneField = new JFormattedTextField(phoneFormat);

        frame.add(phoneField);
        frame.setVisible(true);
    }
}

🔁 Getting & Setting Values

Object val = formattedTextField.getValue();  // Get value
formattedTextField.setValue("123");         // Set value

🧠 Tips

  • Use setFocusLostBehavior(JFormattedTextField.COMMIT) to ensure formatting on focus lost.

  • You can use getText() for raw string, but getValue() is preferred for formatted data types.

Would you like an example combining this with JButton to validate and show the input?

Comments

Popular posts from this blog

Remove (Clear) and remove Selected element

JSpinner

🛢️ MySQL Connection & CRUD Operations in Java