2014-04-19 45 views
0

我試圖把一起被別人一個我需要做定製PlainDocument,但因爲我不知道PlainDocument的機制,我失敗了,也沒有工作。我需要一些能夠確保我的文本字段只允許2個字母的東西,所以任何只出現兩次的a-zA-Z。我先試了這個:想不通這有什麼錯我的DocumentFilter

public class LetterDocument extends PlainDocument { 

    private String text = ""; 

    @Override 
    public void insertString(int offset, String txt, AttributeSet a) { 
     try { 
      text = getText(0, getLength()); 
      if ((text + txt).matches("^[a-zA-Z]{2}$")) { 
       super.insertString(offset, txt, a); 
      } 
     } catch (Exception ex) { 
      Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     } 
    } 

這甚至不讓我輸入任何東西。那麼我想這一點,我試圖從其他兩個線程,其中一個讓只有字母鍵入,和其他限制的人物放在一起:

public class LetterDocument extends PlainDocument { 
    private int limit; 
    private String text = ""; 

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

    @Override 
    public void insertString(int offset, String txt, AttributeSet a) 
      throws BadLocationException { 
     if (txt == null) 
      return; 
     try { 
      text = getText(0, getLength()); 

      if (((text + txt).matches("[a-zA-Z]")) 
        && (txt.length()) <= limit) { 
       super.insertString(offset, txt, a); 
      } 
     } catch (Exception ex) { 
      Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE, 
        null, ex); 
     } 

    } 
} 

我不知道什麼是錯的。

回答

2

請勿使用自定義文檔。請使用DocumentFilter。請閱讀Swing教程Implementing a Document Filter中的部分,以瞭解可以在文檔中輸入的字符數量的實際示例。

然後只需添加一些額外的邏輯,以確保只有字母被添加。

或者更簡單的選擇是使用帶字符掩碼的JFormatttedTextField。請再次參閱Using a Formatted Text Field上的教程。

+0

我使用的屏蔽格式爲我的phoneNumber的和郵政編碼文本框,因爲它們需要二維口罩(字符極限和模板),我用某個DocumentFilter的地址,城市,名字,因爲我只想把它限制在人物和我不太在意大小。謝謝! – Abdul

+0

還,我沒有得到任何錯誤,但大約是JTextField的一切,JFormattedTextField中相同,如方法,具有靈活性的例外呢?我在問我是否需要通過並進行修改。 – Abdul

相關問題