Character 限制JTextField字符输入

Character 限制JTextField字符输入,character,limit,document,jtextfield,Character,Limit,Document,Jtextfield,所以我搜索了整个互联网,在每一个主题中我都找到了这个限制JTextField输入的解决方案 public class FixedDocument extends PlainDocument { private int limit; // optional uppercase conversion private boolean toUppercase = false; FixedDocument(int limit) { super(); this.limit =

所以我搜索了整个互联网,在每一个主题中我都找到了这个限制JTextField输入的解决方案

public class FixedDocument extends PlainDocument {
  private int limit;
  // optional uppercase conversion
  private boolean toUppercase = false;

  FixedDocument(int limit) {
   super();
   this.limit = limit;
   }

  FixedDocument(int limit, boolean upper) {
   super();
   this.limit = limit;
   toUppercase = upper;
   }

  public void insertString (int offset, String  str, AttributeSet attr) throws BadLocationException {
   if (str == null){
       return;
   }
    if ((getLength() + str.length()) <= limit) {
     if (toUppercase) str = str.toUpperCase();
     super.insertString(offset, str, attr);
     }
   }
}

有人知道我做错了什么吗?

你的问题是导入了错误的AttributeSet类。您正在导入
javax.print.attribute.AttributeSet
,而您应该导入
javax.swing.text.AttributeSet
,错误消息告诉您这一点。同样,我自己也会使用DocumentFilter,因为这就是它的构建目的。

我自己也会使用DocumentFilter。
no suitable method found for insertString(int,java.lanf.String,javax.print.attribute.AttributeSet)
 method javax.swing.text.PlainDocument.insertString(int,java.lang.String,javax.text.AttributeSet) is not applicable
  (actual argument javax.printattribute.AttributeSet cannot be converted to javax.swing.text.AttributeSet by method invocation conversion)