Adel
Adel

Reputation: 6278

How can I set text to null of JTextFields at runtime?

Can someone please help me how to set Text to null of JTextFields at runtime, I want my text field to be empty when length of the equal "13" . It will ask the user to enter The text (code have size 13 max) , then the input will changed to null for another process.

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("");                
 }                
}

i get the nex error:

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)

Upvotes: 1

Views: 4337

Answers (2)

camickr
camickr

Reputation: 324128

You can't update a Document from within the DocumentListener. Wrap the code in an invokeLater() so the code is added to the end of the EDT.

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

Upvotes: 3

Reimeus
Reimeus

Reputation: 159804

A DocumentListener cannot be used to modify the underlying Document of a JTextComponent. Use a DocumentFilter instead.

Adding:

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

The 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);
      }
   }
}

Upvotes: 4

Related Questions