Building a Java text editor
To do this, you'll add a String
instance variable to hold the name of the file that was opened and add methods for writing the text back out to that file and to other files.
jFileChooser1
in the structure pane. This will take you to the last entry in the list of instance variable declarations (since jFileChooser1
was the last declaration made).
jFileChooser1
:
String currFileName = null; // Full path with filename. null means new / untitled. boolean dirty = false; // True means modified text.
openFile(String fileName)
method in the structure pane to quickly locate it in the source code. Place the cursor in that method after the following line that reads the file into the JTextArea
:
jTextArea1.setText(new String(data, 0, chars_read));
// Cache the currently opened filename for use at save time... this.currFileName = fileName; // ...and mark the edit session as being clean this.dirty = false;
saveFile()
method that you can call from the File|Save event handler. You can place it just after the openFile()
method:
// Save current file; handle not yet having a filename; report to statusBar. boolean saveFile() { // Handle the case where we don't have a file name yet. if (currFileName == null) { return saveAsFile(); } try { // Open a file of the current name. File file = new File (currFileName); // Create an output writer that will write to that file. // FileWriter handles international characters encoding conversions. FileWriter out = new FileWriter(file); String text = jTextArea1.getText(); out.write(text); out.close(); this.dirty = false; return true; } catch (IOException e) { statusBar.setText("Error saving "+currFileName); } return false; }
saveAsFile()
method that is called from saveFile()
if there is no current filename. It will also be used from the File|Save As menu later. Put the following code right after the saveFile()
method:
// Save current file, asking user for new destination name. // Report to statuBar. boolean saveAsFile() { // Use the SAVE version of the dialog, test return for Approve/Cancel if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog(this)) { // Set the current file name to the user's selection, // then do a regular saveFile currFileName = jFileChooser1.getSelectedFile().getPath(); //repaints menu after item is selected this.repaint(); return saveFile(); } else { this.repaint(); return false; } }
actionPerformed()
event handler for the File|Save menu item (jMenuItem3
).
Insert the following code:
//Handle the File|Save menu item. saveFile();
actionPerformed()
event handler for the File|Save As menu item (jMenuItem4
) and insert the following code:
//Handle the File|Save As menu item. saveAsFile();
Warning: This is now a functioning text editor. Don't damage important source files while testing it.