请勿为此使用KeyListener,因为你会错过很多内容,包括粘贴文本。同样,KeyListener是一个非常低级的构造,因此在Swing应用程序中应避免使用它。
SO上已经多次描述了该解决方案:使用documentFilter。这个站点上有几个示例,其中一些是我写的。
例如:using-documentfilter-filterbypass
同样对于教程帮助,请查看:实现documentFilter。
编辑
例如:
import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.text.AttributeSet;import javax.swing.text.BadLocationException;import javax.swing.text.document;import javax.swing.text.documentFilter;import javax.swing.text.Plaindocument;public class DocFilter { public static void main(String[] args) { JTextField textField = new JTextField(10); JPanel panel = new JPanel(); panel.add(textField); Plaindocument doc = (Plaindocument) textField.getdocument(); doc.setdocumentFilter(new MyIntFilter()); JOptionPane.showMessageDialog(null, panel); }}class MyIntFilter extends documentFilter { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { document doc = fb.getdocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.insert(offset, string); if (test(sb.toString())) { super.insertString(fb, offset, string, attr); } else { // warn the user and don't allow the insert } } private boolean test(String text) { try { Integer.parseInt(text); return true; } catch (NumberFormatException e) { return false; } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { document doc = fb.getdocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.replace(offset, offset + length, text); if (test(sb.toString())) { super.replace(fb, offset, length, text, attrs); } else { // warn the user and don't allow the insert } } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { document doc = fb.getdocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.delete(offset, offset + length); if (test(sb.toString())) { super.remove(fb, offset, length); } else { // warn the user and don't allow the insert } }}为什么这很重要?
- 如果用户使用复制和粘贴将数据插入文本组件怎么办?KeyListener可以错过吗?
- 你似乎希望检查数据是否可以表示int。如果他们输入了不合适的数字数据怎么办?
- 如果要允许用户以后输入重复数据怎么办?用科学计数法?



