如何在Java GUI中仅允许使用大写字母? [英] How to only allow capital letters in Java GUI?
本文介绍了如何在Java GUI中仅允许使用大写字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望只能在我的GUI中输入大写字母,所以我只需要最简单的方法来限制/阻止人们输入小写字母.
I want to be able to input only capital letters to my GUI and so I just need the easiest way to cap/stop people from entering lowercase.
JTextField jt = new JTextField(12);
推荐答案
使用看看实现文档过滤器以获取详细信息,并以 MDP的博客为例
Take a look at Implementing a Document Filter for details and MDP's Weblog for examples
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 GUI中仅允许使用大写字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文