2010-12-23 65 views
0

我試圖限制JTextField中輸入的字符數的字符數......爲此我創建這樣的一個類:無法設置限制的JTextField

class JTextFieldLimiter extends PlainDocument 
    { 
     private int limit; 
     JTextFieldLimiter(int limit) 
     { 
      super(); 
      this.limit= limit; 
     } 
     public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { 
     if (str == null) 
      return; 

     if ((getLength() + str.length()) <= limit) { 
      super.insertString(offset, str, attr); 
     } 
     } 
    } 

我認爲這必須工作正常,但編譯器顯示錯誤,它說:

cannot find symbol: method insertString(int,java.lang.String,javax.print.attribute.Attributeset) 
location:class javax.swing.text.PlainDocument 
super.insertString(offset,str,(AttributeSet) attr); 
    ^

代碼有什麼問題?

+0

你的開啓和關閉大括號在你的實際代碼中是否正確排列?你在這段代碼中遺漏了一個右大括號... – irrelephant 2010-12-23 08:29:38

+0

對不起......實際代碼很好..... – sasidhar 2010-12-23 08:34:55

回答

2

您正在使用錯誤的AttributeSet。檢查你的進口。

它應該是:

javax.swing.text.AttributeSet 

不是:

javax.print.attribute.Attributeset 
0

創建自定義文檔而不是一個更好的解決方案是使用某個DocumentFilter。然後這可以用於JTextField或JTextArea或JTextPane。閱讀Swing教程中有關How to Write a Document Filter的部分以獲得一個工作示例。

0

如果您只想限制JTextField中的字符數,我會避免使用Document或DocumentFilter。你可以只覆蓋的keyTyped()事件,像這樣的例子:

txtGuess = new JTextField(); 
txtGuess.addKeyListener(new KeyAdapter() { 
    public void keyTyped(KeyEvent e) { 
     if (txtGuess.getText().length() >= 3) // limit textfield to 3 characters 
      e.consume(); 
    } 
}); 

這限制字符數的猜謎遊戲文本字段3個字符,通過重寫的keyTyped事件,並檢查是否文本字段已經有3個字符 - 如果是這樣,你正在「消費」關鍵事件(e),以免它像正常一樣得到處理。

我的一個學生問了這個問題,其他答案在StackOverflow上都不如我給他們的答案那麼簡短,所以我想我會張貼討論:)。乾杯!