0

I want to know if there is a way to notice if a listener is changing the text of a JTextField or if it is done by .setText(); I need to seperate between both cases, beacause it need to do different things when accesed by a user or by the programm.

carlos.gmz
  • 100
  • 8
  • 1
    Possible duplicate of [Value Change Listener to JTextField](https://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield) (out of dupe-close-votes) – Hovercraft Full Of Eels Jan 31 '21 at 22:59
  • 2
    Use a DocumentListener, as the duplicate mentions, but turn it off when the program changes the text field's value, and back on again when the program is done changing. A simple boolean flag will suffice to allow you to do this. – Hovercraft Full Of Eels Jan 31 '21 at 23:00

1 Answers1

1

I assume you use a DocumentListener to hook into user's input. You can remove this document listener while you call the setText from your program.

Take a look at the following example. When the button is pressed, the text is changed without the printing message.

public class DocumentListenerExample extends JFrame {
    private JTextField textField;
    private DocumentListener textFieldDocumentListener;

    public DocumentListenerExample() {
        super("");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new FlowLayout());

        textField = new JTextField(20);
        textFieldDocumentListener = new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                System.out.println("Text changed by user");
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                System.out.println("Text changed by user");
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                System.out.println("Text changed by user");
            }
        };
        textField.getDocument().addDocumentListener(textFieldDocumentListener);

        add(textField);

        JButton button = new JButton("Change text");
        button.addActionListener(e -> {
            textField.getDocument().removeDocumentListener(textFieldDocumentListener);
            textField.setText(String.valueOf(Math.random()));
            textField.getDocument().addDocumentListener(textFieldDocumentListener);
        });

        add(button);

        pack();
        setLocationByPlatform(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new DocumentListenerExample().setVisible(true);
        });
    }
}
George Z.
  • 6,643
  • 4
  • 27
  • 47