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.example.swing;

import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.*;

public class DocumentFilterExample extends JFrame {
    public DocumentFilterExample() throws HeadlessException {

    protected void initComponents() {
        setSize(250, 250);
        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();

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

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

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

    class UppercaseDocumentFilter extends DocumentFilter {

        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            fb.insertString(offset, text.toUpperCase(), attr);

        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, text.toUpperCase(), attrs);

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia 🇮🇩. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply