Building a Java text editor
JTextArea
so your program will be setting the dirty
flag whenever typing occurs. To do this, you need to add a Swing DocumentListener
to the jTextArea
's document (model) and check for insert, remove, and changed events.
jTextArea1
.
document
property in the left column of the Inspector, then right-click and choose Expose As Class Level Variable.
A document1
object is placed in the Other
folder of the component tree where you can now set its properties and events.
document1
in the tree, then switch to the Events tab in the Inspector and create a changedUpdate()
event. Notice that the following DocumentListener
was added to the jbInit()
:
document1.addDocumentListener(new TextEditFrame1_document1_documentAdapter(this));
void document1_changedUpdate(DocumentEvent e)
event:
dirty = true;
document1
, and create two more events from the Inspector for document1
: insertUpdate()
and removeUpdate()
. Insert the same line of code in these events that you used in the changedUpdate()
event.
This will make sure that any character typed in the text area will force the dirty
flag to true.
okToAbandon()
method so that now it will really be testing the dirty
flag:
if (!dirty) { return true; }The
okToAbandon()
method should now look like this:
// Check if file is dirty. // If so get user to make a "Save? yes/no/cancel" decision. boolean okToAbandon() { if (!dirty) { return true; } int value = JOptionPane.showConfirmDialog(this, "Save changes?", "Text Edit", JOptionPane.YES_NO_CANCEL_OPTION) ; switch (value) { case JOptionPane.YES_OPTION: // yes, please save changes return saveFile(); case JOptionPane.NO_OPTION: // no, abandon edits // i.e. return true without saving return true; case JOptionPane.CANCEL_OPTION: default: // cancel return false; } }