2012-04-28 256 views
1

所以我搜索了整个互联网,并在每一个主题中,我找到了限制JTextField输入的解决方案。限制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); 
    } 
    } 
} 

但我有一个代码的问题。此代码行“super.insertString(offset,str,attr);”给我错误:

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) 

任何人有任何想法我在做什么错在这里?

+0

我会为此使用一个DocumentFilter。 – 2012-05-09 16:05:52

回答

2

你的问题是你导入了错误的AttributeSet类。您正在导入javax.print.attribute.AttributeSet,当您应该导入javax.swing.text.AttributeSet时,错误消息几乎告诉你这一点。再次,我自己,我会为此使用DocumentFilter,因为它是为它构建的。

+0

得到它的工作:)谢谢。 – 2012-05-09 16:50:48