Search code examples
javaswingactionjtextcomponentdocumentlistener

Using Actions with DocumentListener


I'm developing an application where I want something to be triggered both by the user updating the contents of a JTextArea, or manually via pressing a JButton.

I have done the first part using a DocumentListener and putting the relevant code in its insertUpdate method.

I haven't used Actions before, but I've heard they are useful for situations where you need something to be triggered by multiple controls. Is it possible to trigger the action from the DocumentListener? Is it a good idea to use Actions at all, or should I just put my code in a normal method?

(in the constructor):

    textAreaInput.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            // do something
        }
        public void removeUpdate(DocumentEvent e) {}
        public void changedUpdate(DocumentEvent e) {}
    });

and the Action, which is a field:

Action doSomething = new AbstractAction("Do Something!") {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do it
    }
};

clarification:

The JTextArea will receive text that is pasted in by the user, which I want to parse automatically. The parsing depends on other values set elsewhere in the GUI; if the user changes these other values, he may want to re-parse the text, hence the need to perform the same action by pressing a button.


Solution

  • You can invoke the actionPerformed() method, whether it's in an Action or not. There's an example here.