如何在Java GUI中只允许大写字母?

Leh*_*789 3 java swing text jtextfield uppercase

我希望能够只输入大写字母到我的GUI,所以我只需要最简单的方法来限制/阻止人们输入小写.

JTextField jt = new JTextField(12);
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 6

用一个 DocumentFilter

看看实现一个文件过滤器的详细信息和MDP的博客的例子

属于我们

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class UppercaseTest {

    public static void main(String[] args) {
        new UppercaseTest();
    }

    public UppercaseTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(20);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter() {

                    @Override
                    public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                        string = string.toUpperCase();
                        super.insertString(fb, offset, string, attr);
                    }

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

                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
Run Code Online (Sandbox Code Playgroud)