注意是 JTextField
JTextField 没有 下面的方法
Document doc = new PlainDocument()
JTextArea text = new JTextArea(doc);
------解决方案--------------------
监听事件是不靠谱的,按下去后确实可以删除,但是那个输入的字符要先显示到文本框里,然后被自动删除,体验相当不好
PlainDocument是可以的,假如是只输入数字:
- Java code
import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class NumOnly extends PlainDocument{ public void insertString(int offs,String str,AttributeSet a) throws BadLocationException{ for(int i=0;i<str.length();i++){ if(str.charAt(i)<'0'||str.charAt(i)>'9'){ return; } } super.insertString(offs,str,a); }}