如何在运行时将文本设置为空的JTextField?

时间:2013-07-16 00:30:52

标签: java swing runtime jtextfield

有人可以帮我解决如何在运行时将Text设置为null的JTextFields, 我希望我的文本字段在等于“13”的长度时为空。 它将要求用户输入文本(代码的大小最大为13),然后输入将更改为null以进行另一个过程。

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)

2 个答案:

答案 0 :(得分:4)

DocumentListener不能用于修改Document的基础JTextComponent。请改用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);
      }
   }
}

答案 1 :(得分:3)

您无法从DocumentListener中更新文档。将代码包装在invokeLater()中,以便将代码添加到EDT的末尾。

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