How to ask if I have saved my text document before closing the jframe

99 Views Asked by At

I'm developing a text editor and I need to check whether I have saved chances typed (even a space) in my Text Area.

If I have typed even a space, the dialog should pop and ask me to save the text before closing the application.

I need to define all the keys in a single way without checking all the keyboards keys are pressed or not... This is my code:

 private void isAnyKeyWasPressed() {
    jTextPane1.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar()==e.VK_0 || e.getKeyChar()==e.VK_1) {//need to define all the keyboard keys without defining one by one like this
                //my dialog box goes here
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
}
2

There are 2 best solutions below

1
Markus Fischer On BEST ANSWER

If I understand you correctly, you are asking how to detect whether a document in a JTextPane was edited or not. Listening to keys is not optimal. I would rather recommend one of two ways:

A) Listen to changes to the underlying document:

    jTextPanel.getDocument().addDocumentListener(new DocumentListener(){
        @Override
        public void changedUpdate(DocumentEvent e) {
            isModified=true;                
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            isModified=true;                
        }
        @Override
        public void removeUpdate(DocumentEvent e) {
            isModified=true;                
        }            
    });

The field isModified has to be initialized to false, and will be set to truewhenever the document is changed in any way. You have to reset it to false after saving.

B) Keep a copy of the original document and compare both when the frame is about to be closed. How you do this depends a bit on the kind of document that you have. If it is an HTMLDocument, then comparing the actual HTML source code is the most accurate method:

Before editing starts:

HTMLDocument doc=(HTMLDocument)jTextPanel.getDocument();
String originalHtml=getHTML(doc);

After editing / upon closing the frame:

HTMLDocument doc=(HTMLDocument)jTextPanel.getDocument();
String editedHtml=getHTML(doc);
if(!editedHtml.equals(originalHtml))
   // ... text has been edited

The getHTML() method:

public String getHTML(HTMLDocument doc){
    StringWriter writer = new StringWriter();
    kit.write(writer, doc, 0, doc.getLength());
    return writer.toString();
}

The advantage of approach B) is that you don't have to check each edit operation (the overhead of which is negligible in most cases, though) and that you can accurately detect when changes have been reverted (e.g. user added text, then deleted that text, or an undo has been performed).

4
GhostCat On

You do not want to listen for key events.

Instead, you want to track a "unsaved property" within the class that wraps around your different components. Any time the user makes any change to the editor (more specifically to the underlying model object); you set that property to true.

Every time the user saves, you turn the property to false.

And whenever the user tells the application to shutdown, you check that property, and if it is true - you ask the user if he wants to save.

Do not get into a mode where "one action" directly triggers another one.

Edit: just to make that clear - with property I mean that you add a field to your class, very much like the isModified that the other answer already suggests.