Oronce SOSSOU
Oronce SOSSOU

Reputation: 13

Is there a way to call JTextField.setText() without fired DocumentListener's removeupdate()?

I'm actually learning Java Swing API by working on this small project.

This is the code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import com.userView.Utilities;

public class MobileNumberValidation extends JFrame {

    private JButton clearButton ;
    private JTextField mobileNumberField ;
    private JLabel mobileNumberLabel ;
    private JLabel errorMessage ;


    MobileNumberValidation(){

        //Intializing the instance variables
        clearButton       = new JButton("clear");
        mobileNumberField = new JTextField();
        mobileNumberLabel = new JLabel("TEL");
        errorMessage      = new JLabel("Tel is empty");

        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        //add components to Jframe
        add(mobileNumberField);
        add(clearButton);
        add(mobileNumberLabel);
        add(errorMessage);


        //set components location
        mobileNumberField.setBounds(200, 170, 230, 20);
        clearButton.setBounds(200, 220, 100, 20);
        mobileNumberLabel.setBounds(160, 170, 100, 20);
        errorMessage.setBounds(210, 190, 300,20);


        //components style
        errorMessage.setForeground(Color.decode("#CD5C5C"));

        //add listener and handle event
        mobileNumberField.getDocument().addDocumentListener(new DocumentListener(){
            
            @Override
            public void changedUpdate(DocumentEvent arg0) {                
            }

            @Override
            public void insertUpdate(DocumentEvent arg0) {
                processTelValidation();
            }

            @Override
            public void removeUpdate(DocumentEvent event) {
                System.out.println("removeUpdate");
                processTelValidation();
            }

            public void processTelValidation() {
                if (Utilities.isRegExPatternMatching("^0[0-9]{6}$", mobileNumberField.getText())) {
                    errorMessage.setVisible(false);
                }else{
                    errorMessage.setVisible(true);
                    errorMessage.setText("enter a valid Tel number");
                }
            }
        });

        clearButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                //clear mobileNumberField
                mobileNumberField.setText("");
            }
        });
    }

    public static void main(String[] args) {
        
       new MobileNumberValidation();
        
    }

}

app screen shot

Each time I press the clearButton to clear the field, mobileNumber.setText("") get called and it's fired removeUpdate() from DocumentListener and I don't want that.

Do you know any other way to clean the field of a JTextField component or using JTextField.setTextField() but without fired DocumentListener method?

Upvotes: 0

Views: 328

Answers (1)

George Z.
George Z.

Reputation: 6808

You can simply keep the listener in a local variable. Then, remove the listener from the Document, clear the text and finally put the listener back on the Document:

(Keep in mind I removed one line of yours: if (Utilities.isRegExPatternMatching("^0[0-9]{6}$", mobileNumberField.getText())) )

public class MobileNumberValidation extends JFrame {

    private JButton clearButton;
    private JTextField mobileNumberField;
    private JLabel mobileNumberLabel;
    private JLabel errorMessage;

    MobileNumberValidation() {

        // Intializing the instance variables
        clearButton = new JButton("clear");
        mobileNumberField = new JTextField();
        mobileNumberLabel = new JLabel("TEL");
        errorMessage = new JLabel("Tel is empty");

        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        // add components to Jframe
        add(mobileNumberField);
        add(clearButton);
        add(mobileNumberLabel);
        add(errorMessage);

        // set components location
        mobileNumberField.setBounds(200, 170, 230, 20);
        clearButton.setBounds(200, 220, 100, 20);
        mobileNumberLabel.setBounds(160, 170, 100, 20);
        errorMessage.setBounds(210, 190, 300, 20);

        // components style
        errorMessage.setForeground(Color.decode("#CD5C5C"));

        // add listener and handle event
        DocumentListener validatePhoneListener = new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent arg0) {
            }

            @Override
            public void insertUpdate(DocumentEvent arg0) {
                processTelValidation();
            }

            @Override
            public void removeUpdate(DocumentEvent event) {
                System.out.println("removeUpdate");
                processTelValidation();
            }

            public void processTelValidation() {
                if (Math.random() > 0.5d) {
                    errorMessage.setVisible(false);
                } else {
                    errorMessage.setVisible(true);
                    errorMessage.setText("enter a valid Tel number");
                }
            }
        };
        mobileNumberField.getDocument().addDocumentListener(validatePhoneListener);

        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                mobileNumberField.getDocument().removeDocumentListener(validatePhoneListener);
                mobileNumberField.setText("");
                mobileNumberField.getDocument().addDocumentListener(validatePhoneListener);
            }
        });
    }

    public static void main(String[] args) {

        new MobileNumberValidation();

    }

}

Also, make sure you that you have read:

  1. Why null layouts and absolute positions are bad practice in Swing?
  2. SwingUtilities.invokeLater() why is it needed?

Upvotes: 5

Related Questions