Java Swing - detecting document changes

At school, I am trying to recreate a Microsoft Notepad program using Java Swing. I am working on saving and opening .txt files, and I am trying to figure out a way for the program to detect changes made to a document. If a change is detected and the user chooses to open or create a new file, I want the program to ask the user if they want to save their changes before proceeding.

My thought for doing this was to create a flag called documentChanged

, which would initially be false, and which would be set to true when changes were made to JTextArea

. To detect this change, I thought of using it TextListener

like this:

public class JNotepad implements ActionListener
{
    boolean documentChanged;
    JTextArea notepad;

    JNotepad()
    {
        documentChanged = false;

        notepad = new JTextArea();
        notepad.addTextListener(new TextListener() {
            public void textValueChanged(TextEvent te) {
                documentChanged = true;
            }
        });
    }
}

      

However, I found out that Java classes cannot implement multiple interfaces at once, and I already use ActionListener

to implement items in your notepad's menu bar.

My question is, is there a way to use both TextListener

and ActionListener

(or any other listener) simultaneously in the same class? If not, what would be my best course of action for document change detection?

+3


source to share


2 answers


How do you even compile this

notepad = new JTextArea();
notepad.addTextListener(new TextListener() {
   // ....
}

      

as TextListeners are not defined to work with JTextAreas, but rather TextAreas, a completely different beast.

You have to add a DocumentListener to your JTextArea Document.

notepad.getDocument().addDocumentListener(new DocumentListener() {
    void insertUpdate(DocumentEvent e) {
        documentChanged = true;
    }

    void removeUpdate(DocumentEvent e) {
        documentChanged = true;
    }

    void changedUpdate(DocumentEvent e) {
        documentChanged = true;
    }

});

      




Relatively

My question is, is there a way to use both TextListeners and ActionListeners (or any other listener) at the same time in the same class?

Using a DocumentListener has nothing to do with ActionListeners used elsewhere in your program, since their domains are orthogonal to each other, i.e. one has absolutely nothing to do with the other.

+2


source


This was the answer in another post. See Changed text in JTextArea? How?



And also see How to write a document listener ( DocumentListener

) in Oracle, you will see an example applet.

+3


source







All Articles