2012-04-28 253 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