2013-05-21 53 views
1

我有這樣的代碼,在一個JTextField是「禁用」用戶輸入後n個字符插入:塊文字書寫後n個字符

JTextField tf = new JTextField(); 
tf.addKeyListener(new KeyAdapter() { 
    public void keyTyped(KeyEvent e) { 
     if (((JTextField) e.getSource()).getText().length() > n) { 
      e.consume(); 
     } 
    } 
}); 

它的工作原理,但我想知道如果有一個選擇,因爲我在一臺舊的慢速電腦上試了一次,當我在文本框中輸入某些東西時,信件被添加了,然後它消失了......我想避免在用戶輸入後使用e.consume(),並直接阻止插入。

可能嗎?

編輯

我忘了提,我只是在這個例子中使用JTextField,但我想這個代碼與普通的文本輸入組件的工作像JTextPaneJTextArea

+0

這可能幫助:http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters- in-jtextfield –

+0

看起來像documentFilter是所有這些情況下的方式。 JTextPane支持文檔,至於JTextArea:http://www.linuxquestions.org/questions/programming-9/java-jtextarea-limiting-amount-of-characters-entered-155469/#post805335 –

+0

任何實現JTextComponent '界面有一個文件。如果特定文檔支持setDocumentFilter(例如'AbstractDocument'),則可以使用此方法。 http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html。 –

回答

3

您可以使用在DocumentSizeFilter

這是該具體使用由: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/DocumentSizeFilter.java

教程就如何做到這一點內實現文檔過濾科:

從那裏報價:

要限制所允許的文檔中的字符,DocumentSizeFilter 將重寫DocumentFilter類的insertString方法,即每次將文本插入文檔時調用。它也 覆蓋替換方法,這是最有可能被調用時,用戶粘貼在新的文本中 。通常,當用戶輸入或粘貼新文本時,或者調用setText方法 時,文本插入可能導致 。這裏是DocumentSizeFilter類的實現的 的insertString方法:

public void insertString(FilterBypass fb, int offs, 
         String str, AttributeSet a) 
    throws BadLocationException { 

    if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) 
     super.insertString(fb, offs, str, a); 
    else 
     Toolkit.getDefaultToolkit().beep(); }