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

标签 java swing text jtextfield uppercase

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

JTextField jt = new JTextField(12);

最佳答案

使用 DocumentFilter

看看Implementing a Document Filter详情和MDP's Weblog例如

Belong to Us

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);
            }
        });
    }

}

关于java - 如何在 Java GUI 中只允许大写字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618998/

相关文章:

java - 在此字符串操作期间将创建多少个对象?

java - ZipOutputStream 相对路径

java - 显示标签Struts 2导出不显示PDF

java - 如何在 Jlist 中添加两列?

java - 使用数据库创建 jcomponents

java - 如何设置文本格式?

java - 为什么 JDBC 将端口 0 视为与空(默认)端口相同?

java - Java 中用于拖动组件的 Swing 库

c# - AvalonEdit 插入文本不起作用

text - NANO 中一行 "Comment"的键盘快捷键?