您可能希望改用文档过滤器。
这将允许您构建过滤器来限制用户实际键入的内容,而不是依赖于后验证。
在此处查看一些示例
更新
这非常简单。使用我链接的示例。我相信您将能够根据您的需要调整它们。
public class TestDocumentFilter01 {
public static void main(String[] args) {
new TestDocumentFilter01();
}
public TestDocumentFilter01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(createField("1234567890"), gbc);
add(createField("stackoverflow"), gbc);
add(createField("abcdefghijklmnopqrstuvwxyz "), gbc);
}
protected JTextField createField(String mask) {
JTextField field = new JTextField(10);
MaskFilter df = new MaskFilter();
df.setMask(mask);
((AbstractDocument) (field.getDocument())).setDocumentFilter(df);
return field;
}
}
public class MaskFilter extends DocumentFilter {
private char[] maskSet;
private String mask;
public void setMask(String mask) {
this.mask = mask;
this.maskSet = mask.toCharArray();
Arrays.sort(this.maskSet);
}
public String getMask() {
return mask;
}
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
StringBuffer buffer = new StringBuffer(string);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (Arrays.binarySearch(maskSet, ch) < 0) {
buffer.deleteCharAt(i);
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}