2013-07-16 42 views
1

是否有人可以幫助我如何在運行時將文本設置爲空JTextFields, 我希望我的文本字段在等於「13」的長度時爲空。 它會要求用戶輸入文本(代碼的大小爲13 max),那麼對於另一個進程,輸入將更改爲null。如何在運行時將文本設置爲null的JTextFields?

code = new JextField(15); 
code.setForeground(new Color(30, 144, 255)); 
code.setFont(new Font("Tahoma", Font.PLAIN, 16)); 
code.setHorizontalAlignment(SwingConstants.CENTER); 
code.setBounds(351, 76, 251, 38); 
panel_2.add(code); 

code.getDocument().addDocumentListener(new DocumentListener() { 
public void changedUpdate(DocumentEvent e) { 
    test(); 
} 
public void removeUpdate(DocumentEvent e) { 
    test(); 
} 
public void insertUpdate(DocumentEvent e) { 
    test(); 
} 
public void test() { 
if(code.getText().length()==13){     
    code.setText("");     
}     
} 

我得到的NEX錯誤:

java.lang.IllegalStateException: Attempt to mutate in notification 
    at javax.swing.text.AbstractDocument.writeLock(Unknown Source) 
    at javax.swing.text.AbstractDocument.replace(Unknown Source) 
    at javax.swing.text.JTextComponent.setText(Unknown Source) 

回答

3

你不能從內部的DocumentListener更新文檔。將代碼包裝在invokeLater()中,以便將代碼添加到EDT的末尾。

SwingUtilities.invokeLater(new Runnable() 
{ 
    public void run() 
    { 
     if (code.getDocument().getLength() >= 13) 
     {     
      code.setText("");     
     } 
    } 
}); 
4

DocumentListener不能被用來修改一個JTextComponent的底層Document。改爲使用DocumentFilter

添加:

AbstractDocument d = (AbstractDocument) code.getDocument(); 
d.setDocumentFilter(new MaxLengthFilter(13)); 

DocumentFilter

static class MaxLengthFilter extends DocumentFilter { 

    private final int maxLength; 

    public MaxLengthFilter(int maxLength) { 
     this.maxLength = maxLength; 
    } 

    @Override 
    public void replace(DocumentFilter.FilterBypass fb, int offset, 
     int length, String text, AttributeSet attrs) 
       throws BadLocationException { 

     int documentLength = fb.getDocument().getLength(); 
     if (documentLength >= maxLength) { 
     super.remove(fb, 0, documentLength); 
     } else { 
     super.replace(fb, offset, length, text, attrs); 
     } 
    } 
} 
相關問題