How do I format JTextField text to uppercase?

To change JTextField text to upper case can be easily done by adding a DocumentFilter to the JTextField component using the setDocumentFilter() method. The DocumentFilter allow us to filter action for changes in the document such as insert, replace and remove.

The code snippet below show us how to do it.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class DocumentFilterExample extends JFrame {
    public DocumentFilterExample() throws HeadlessException {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true));
    }

    protected void initComponents() {
        setSize(500, 500);
        setTitle("DocumentFilter Example");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField firstName = new JTextField();
        firstName.setPreferredSize(new Dimension(150, 20));
        JTextField lastName = new JTextField();
        lastName.setPreferredSize(new Dimension(150, 20));

        DocumentFilter filter = new UppercaseDocumentFilter();
        AbstractDocument firstNameDoc = (AbstractDocument) firstName.getDocument();
        firstNameDoc.setDocumentFilter(filter);

        AbstractDocument lastNameDoc = (AbstractDocument) lastName.getDocument();
        lastNameDoc.setDocumentFilter(filter);

        getContentPane().add(new JLabel("First Name: "));
        getContentPane().add(firstName);
        getContentPane().add(new JLabel("Last Name: "));
        getContentPane().add(lastName);
    }

    static class UppercaseDocumentFilter extends DocumentFilter {
        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
            fb.insertString(offset, text.toUpperCase(), attr);
        }

        @Override
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
            fb.replace(offset, length, text.toUpperCase(), attrs);
        }
    }
}
JTextField Uppercase Text

JTextField Uppercase Text

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.