Java Swing GUI

Convert to Uppercase while Writing in JTextField

In this tutorial, we are going to see how to convert text to uppercase while writing in a JTextField in Java. To change the text of JTextField to uppercase, you can easily do it by adding a DocumentFilter to JTextField component using setDocumentFilter() method. DocumentFilter allows us to filter the action for document changes such as insert, edit and delete.

To convert a string to uppercase, we use toUpperCase() method. To convert it to lower case use toLowerCase() method.

Java Program to Convert to Uppercase while Writing in JTextField
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class UpperTextField extends JFrame 
    public UpperTextField()
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField texte = new JTextField();
        texte.setPreferredSize(new Dimension(180, 20));

        DocumentFilter f = new UppercaseJTextField();
        AbstractDocument doc = (AbstractDocument) texte.getDocument();

        getContentPane().add(new JLabel("Enter text: "));
        setSize(300, 70);

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

    class UppercaseJTextField 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);


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *