How do I associate JLabel component with a JTextField?

In this example we associate a JLabel component with JTextField and JPasswordField using the setLabelFor(). A mnemonic need to be set for the JLabel component and when we press the defined key (ALT+U or ALT+P) a text field will be gained focus.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

public class JLabelSetForTextField extends JFrame {
    public JLabelSetForTextField() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(400, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        JLabel usernameLabel = new JLabel("Username: ");
        JLabel passwordLabel = new JLabel("Password: ");
        JTextField usernameField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        // To make the association between the JLabel and JTextField or
        // JPasswordField we need to define the displayed mnemonic and then
        // call JLabel's setLabelFor method.
        usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U);
        usernameLabel.setLabelFor(usernameField);
        passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P);
        passwordLabel.setLabelFor(passwordField);

        getContentPane().add(usernameLabel);
        getContentPane().add(usernameField);
        getContentPane().add(passwordLabel);
        getContentPane().add(passwordField);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JLabelSetForTextField().setVisible(true);
            }
        });
    }
}

How do I right justified JTextField contents?

To right justified a JTextField contents we can call the setHorizontalAlignment(JTextField.RIGHT) method of the JTextField class.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;

public class TextFieldRightJustify extends JFrame {
    public TextFieldRightJustify() {
        initComponents();
    }

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField textField = new JTextField(15);
        textField.setPreferredSize(new Dimension(100, 20));

        // Right justify the JTextField contents
        textField.setHorizontalAlignment(JTextField.RIGHT);

        container.add(textField);
    }
}

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

How do I add key listener event handler to JTextField?

In this small Swing code snippet we demonstrate how to use java.awt.event.KeyAdapter abstract class to handle keyboard event for the JTextField component. The snippet will change the characters typed in the JTextField component to uppercase.

A better approach for this use case is to use the DocumentFilter class. See the following code snippet How do I format JTextField text to uppercase?.

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 java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

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

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

    protected void initComponents() {
        // Set default form size, closing event and layout manager
        setSize(500, 500);
        setTitle("JTextField Key Listener");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create a label and text field for our demo application and add the
        // component to the frame content pane object.
        JLabel usernameLabel = new JLabel("Username: ");
        JTextField usernameTextField = new JTextField();
        usernameTextField.setPreferredSize(new Dimension(150, 20));
        getContentPane().add(usernameLabel);
        getContentPane().add(usernameTextField);

        // Register a KeyListener for the text field. Using the KeyAdapter class
        // allow us implement the only key listener event that we want to listen,
        // in this example we use the keyReleased event.
        usernameTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                JTextField textField = (JTextField) e.getSource();
                String text = textField.getText();
                textField.setText(text.toUpperCase());
            }
        });
    }
}
JTextField Key Listener

JTextField Key Listener