我希望我的 GUI 只能输入大写字母,所以我只需要最简单的方法来限制/阻止人们输入小写字母。
JTextField jt = new JTextField(12);
最佳答案
看看Implementing a Document Filter详情和MDP's Weblog例如
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/