Skip to content
Tutorials Center
My learning

Topics

Lesson 181 of 201 ยท Projects

Project: A Swing Text Editor

Build a text editor in Java - a document model with undo and redo, find and replace with regex, safe open and save with NIO, and a Swing window with menus.

A text editor seems simple until you write one. Where is "line 3, column 7" in a string? What does Undo undo when you typed a whole sentence? Why does replacing $5 crash? What happens to a Windows file's line endings when a Mac user saves it? What if the power fails halfway through saving? Every one of those questions has a well-known answer, and this project works through them.

You'll build the editor's logic first, as plain Java you can run here: a document model with line and column positions, an undo/redo history built from records, a find-and-replace engine with options, and a file layer on NIO that preserves encodings and line endings. Then you'll connect that logic to Swing's own text components and put it all in a window with a menu, a find bar and a status bar. Our server has no screen, so the window is read-only code for your own computer, but the Swing document model works without a display, and you'll run that part here.

The project uses StringBuilder, records, sealed interfaces with pattern matching, ArrayDeque as a stack, regular expressions, files and charsets, and Swing components and events.

The plan

A good editor is a stack of independent layers. Each stage builds one:

Layer Class Job
Document EditorDocument Holds the text, edits it, converts offsets to lines and columns
History Edit records Remembers every change so it can be undone and redone
Search Finder Finds and replaces text, with case, whole-word and regex options
Files TextFile Opens and saves text safely, keeping the encoding and line endings
Window EditorWindow Swing UI: text area, menus, find bar, status bar

Only the last layer knows about Swing. Everything else is testable logic with no window in sight, which is how professional editors are built too.

Stage 1: a document model

Internally, a document is one long string, and every position in it is an offset: the number of characters before it. Users, however, think in lines and columns. The document's main jobs are to apply edits at offsets and to convert between the two coordinate systems.

The text lives in a StringBuilder, which can insert and delete in the middle without creating a new string for every keystroke. Line breaks are always a single \n inside the editor; Stage 4 deals with \r\n at the file boundary.

Java Stage 1: a document with offsets, lines and columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The document starts with 2 lines, 7 words and 37 characters. After the three edits, 'Friday' sits at offset 35, which is line 2, column 24. The final insert at offset 500 is refused with a clear message instead of StringBuilder's own StringIndexOutOfBoundsException.

Details worth copying into any text-processing code:

  • Lines and columns are 1-based for people, offsets 0-based for code. positionOf counts the \n characters before the offset; the column is the distance from the start of that line, plus one. Off-by-one bugs between the two systems are the most common bug in editor code, so the conversion lives in exactly one place.
  • checkRange runs before every edit. It validates start <= end and both inside the text. StringBuilder.insert(500, ...) would throw too, but its message talks about internal indexes; the document's message talks about the document.
  • A trailing newline doesn't start a new line in the line count. "a\nb\n" is two lines, which is how editors and tools like wc -l count them. Without the special case you'd report a phantom empty third line.
  • Words are runs of non-whitespace, counted with the regex \S+ and Matcher.results().count(). Splitting on whitespace with split("\\s+") gives a wrong count when the text starts with a space, because it produces an empty first element.

Stage 2: undo and redo with records

Undo is the feature users trust most, so it has to be exact. The classic design is the command pattern: every change is stored as an object that knows how to apply itself and how to reverse itself. Java records and a sealed interface make that almost declarative:

  • Insert(offset, text) is undone by deleting that text.
  • Delete(offset, text) remembers the deleted text, so it's undone by inserting it again.
  • Replace(offset, removed, inserted) is undone by a Replace with the two strings swapped.

Two stacks hold the history. Every new edit is pushed on the undo stack and clears the redo stack (once you type something new, the old "future" no longer makes sense). Undo pops an edit, applies its inverse and pushes it on the redo stack; redo does the opposite.

Real editors don't make every keystroke a separate undo step. This version merges consecutive typing into one step, but starts a new step when you type a space after a word, so Undo removes one word at a time.

Java Stage 2: undo, redo and a save point

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Typing "Hello world" one key at a time produces just two undo steps, Hello and world. After saving and making two edits, two undos bring the text back to exactly the saved state, and the (modified) marker disappears. Undo once more and the document is modified again, because it's now older than the saved version. The final delete clears the redo stack, so redo is no longer possible.

How the pieces work:

  • The sealed interface makes the switch exhaustive. apply and inverse handle Insert, Delete and Replace with record patterns and no default. Add a fourth edit type and both methods stop compiling until you handle it. See Sealed Classes and Interfaces and Pattern Matching.
  • "Modified" is a position in the history, not a flag. markSaved remembers which edit was on top of the undo stack at save time. The document is modified whenever the top is a different object. That's why undoing back to the save point clears the marker, something a simple boolean modified can't do. The comparison uses != on purpose: two different edits could be equal records, but only the very same object marks the save point.
  • The save point is never merged into. If typing continued right after a save, merging the next key into the saved edit would replace that object and lose the save point, so perform refuses to merge into it.
  • ArrayDeque is the stack. push, pop and peek work on the front of the deque; the old java.util.Stack class is synchronized and outdated (see Legacy Collections).
  • The history is capped at 200 steps with removeLast(), which drops the oldest edit. Without a limit, a long editing session would keep every keystroke in memory forever.

Stage 3: find and replace

Searching has more options than it seems: match case or not, whole words only, and plain text or a regular expression. The neat trick is that all of them can be expressed as one regex. Plain text is escaped with Pattern.quote, whole-word search wraps the pattern in \b...\b, and ignoring case is a flag. After that, every search is the same Matcher loop.

Java Stage 3: a find-and-replace engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The plain search finds cat five times, including inside Cats and catwalk; whole-word search keeps only cat and CAT. Searching onward from the last match wraps around to the first one at offset 0, as editors do. The literal replacement turns $5 into $6, while the regex \$(\d+) with replacement โ‚ฌ$1 converts both prices. The last search uses a regex with an unclosed parenthesis and gets a readable error instead of a crash.

The pitfalls this design avoids:

  • $ and \ are special in replacement strings. In replaceAll and appendReplacement, $1 means "group 1". A user who replaces price with $5 in plain-text mode would get IllegalArgumentException: Illegal group reference. Matcher.quoteReplacement escapes the replacement, just as Pattern.quote escapes the search text. Forgetting either is the most common find-and-replace bug in Java programs.
  • (?:...) around the pattern before adding \b. Without the group, whole-word search for the regex cat|dog would become \bcat|dog\b, which means "cat at the start of a word, or dog at the end of one".
  • UNICODE_CASE with CASE_INSENSITIVE. By default, case-insensitive matching only folds ASCII letters, so ร‰ wouldn't match รฉ. The extra flag fixes that.
  • Empty matches are skipped. A regex like x* matches the empty string at every position. Selecting an empty match would look like "found nothing" and the cursor would never move.
  • Invalid regexes throw PatternSyntaxException, a subclass of IllegalArgumentException. Its getDescription() and getIndex() give a short message and the position of the problem, better for a status bar than the full multi-line message.

findAll collects every match, which keeps findNext and findPrevious short and correct. For multi-megabyte files you'd search from the caret position with matcher.find(from) instead, but for normal documents the simple version is fast enough.

Stage 4: opening and saving files

Files are where text editors lose people's work, so this layer is careful. A TextFile record holds the text as the editor sees it (with \n line breaks) plus everything needed to write it back the way it was: the path, the charset, the original line separator and whether the file started with a byte order mark.

Java Stage 4: open and save with encodings and line endings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output line by line:

  • The Windows file opens as [UTF-8 with BOM, CRLF]. The editor sees clean \n text without the invisible BOM character at the start. When it saves, the \r\n endings and the BOM come back, so the file still looks right to the Windows tools that created it, and a version-control diff shows only the line you added instead of "every line changed".
  • The ISO-8859-1 file fails as UTF-8. Files.readString decodes strictly: invalid bytes throw MalformedInputException (a CharacterCodingException) instead of silently turning into ? or ๏ฟฝ. The editor catches it and retries with ISO-8859-1, which can decode any byte, and the accented letters appear correctly. If it had guessed wrong silently, the next save would have destroyed those characters for good. Charsets and Encoding explains why.
  • A missing file throws NoSuchFileException, a specific IOException the window can turn into a friendly message.

Saving uses the write-then-move pattern from Files: the new content goes into a temporary file in the same folder, and only a complete file replaces the original. ATOMIC_MOVE makes the replacement a single step on file systems that support it, so a crash leaves either the old file or the new one, never half of each. The temporary file must be in the same folder, because an atomic move can't cross file systems. The finally block deletes the temporary file if anything went wrong before the move.

The record is immutable, so "changing the text" means withText(...), which returns a new TextFile with the same path and format. The window keeps the latest one in a field.

Stage 5: the Swing window

Swing already has a complete text component: JTextArea handles typing, the caret, selection, scrolling, copy and paste. Behind it sits a javax.swing.text.Document (a PlainDocument for a text area), Swing's own version of Stage 1's model, which fires events on every change and records undoable edits. So in the window, EditorDocument gives way to Swing's document, and Stage 2's ideas reappear in Swing's undo classes. The Finder and TextFile classes are used exactly as they are.

Swing's document classes don't need a screen, so you can run them here. This program wires a PlainDocument to an UndoManager and a listener, finds the line and column of the caret using the document's line elements, and runs Replace All as a single undoable step:

Java Stage 5: Swing's document model, undo and Replace All

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what the output shows:

  • Typing fires one event per insertString. In a real window, every keystroke is one insert. The listener is how the window knows to put * in its title.
  • The root element has one child per line. getElementIndex(offset) turns an offset into a line number without scanning the text, because the document keeps the line structure up to date as you type. The text ends with \n, so there's a fourth, empty line element, exactly where the caret would go next.
  • Replace All fires two events (remove, then insert) but is undone in one step. By default the UndoManager would record both edits separately, and the user would need two undos, the first of which would show an empty document. The program temporarily sends the document's edits to a CompoundEdit instead, ends the group, and adds the whole group to the UndoManager as one edit, with a clear menu name.

Here is the complete window. Save it as Main.java, paste the SearchOptions, Match, ReplaceResult and Finder types from Stage 3 and the TextFile record from Stage 4 at the bottom, and run java Main.java.

Java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new EditorWindow().show());
    }
}

class EditorWindow {
    private final JFrame frame = new JFrame();
    private final JTextArea area = new JTextArea(25, 80);
    private final JLabel status = new JLabel(" ");
    private final UndoManager undo = new UndoManager();
    private final JTextField findField = new JTextField(14);
    private final JTextField replaceField = new JTextField(14);
    private final JCheckBox matchCase = new JCheckBox("Match case");
    private final JCheckBox wholeWord = new JCheckBox("Whole word");
    private final JCheckBox regex = new JCheckBox("Regex");
    private TextFile file;              // null until the text is opened or saved
    private boolean modified;

    EditorWindow() {
        area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        area.setTabSize(4);
        area.getDocument().addUndoableEditListener(undo);
        area.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                setModified(true);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                setModified(true);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        area.addCaretListener(e -> updateStatus());

        frame.setJMenuBar(menuBar());
        frame.add(findBar(), BorderLayout.NORTH);
        frame.add(new JScrollPane(area), BorderLayout.CENTER);
        frame.add(status, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (confirmDiscard()) {
                    frame.dispose();
                }
            }
        });
        frame.pack();
        frame.setLocationRelativeTo(null);
        updateTitle();
        updateStatus();
    }

    void show() {
        frame.setVisible(true);
    }

    private JMenuBar menuBar() {
        JMenu fileMenu = new JMenu("File");
        fileMenu.add(item("New", KeyEvent.VK_N, this::newFile));
        fileMenu.add(item("Open...", KeyEvent.VK_O, this::open));
        fileMenu.add(item("Save", KeyEvent.VK_S, this::save));
        fileMenu.add(item("Save As...", 0, this::saveAs));
        JMenu editMenu = new JMenu("Edit");
        editMenu.add(item("Undo", KeyEvent.VK_Z, () -> {
            if (undo.canUndo()) {
                undo.undo();
            }
        }));
        editMenu.add(item("Redo", KeyEvent.VK_Y, () -> {
            if (undo.canRedo()) {
                undo.redo();
            }
        }));
        editMenu.add(item("Find Next", KeyEvent.VK_F, this::findNext));
        JMenuBar bar = new JMenuBar();
        bar.add(fileMenu);
        bar.add(editMenu);
        return bar;
    }

    private JMenuItem item(String text, int key, Runnable action) {
        JMenuItem item = new JMenuItem(text);
        if (key != 0) {
            item.setAccelerator(KeyStroke.getKeyStroke(key,
                java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));   // Ctrl, or Cmd on a Mac
        }
        item.addActionListener(e -> action.run());
        return item;
    }

    private JPanel findBar() {
        JButton next = new JButton("Find next");
        next.addActionListener(e -> findNext());
        JButton replaceAll = new JButton("Replace all");
        replaceAll.addActionListener(e -> replaceAll());
        findField.addActionListener(e -> findNext());      // Enter in the field
        JPanel bar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        bar.add(new JLabel("Find:"));
        bar.add(findField);
        bar.add(new JLabel("Replace:"));
        bar.add(replaceField);
        bar.add(matchCase);
        bar.add(wholeWord);
        bar.add(regex);
        bar.add(next);
        bar.add(replaceAll);
        return bar;
    }

    private SearchOptions options() {
        return new SearchOptions(matchCase.isSelected(), wholeWord.isSelected(), regex.isSelected());
    }

    private void findNext() {
        try {
            Optional<Match> match = Finder.findNext(area.getText(), findField.getText(),
                area.getSelectionEnd(), options());
            match.ifPresentOrElse(
                m -> area.select(m.start(), m.end()),
                () -> status.setText("Not found: " + findField.getText()));
        } catch (IllegalArgumentException e) {           // includes PatternSyntaxException
            status.setText("Search error: " + e.getMessage().lines().findFirst().orElse(""));
        }
    }

    private void replaceAll() {
        try {
            ReplaceResult result = Finder.replaceAll(area.getText(), findField.getText(),
                replaceField.getText(), options());
            if (result.count() > 0) {
                int caret = area.getCaretPosition();
                replaceTextAsOneEdit(result.text());
                area.setCaretPosition(Math.min(caret, result.text().length()));
            }
            status.setText("Replaced " + result.count() + " occurrence(s)");
        } catch (IllegalArgumentException | BadLocationException e) {
            status.setText("Replace error: " + e.getMessage().lines().findFirst().orElse(""));
        }
    }

    /** Replaces the whole text so that one Undo restores it (see the runnable example). */
    private void replaceTextAsOneEdit(String newText) throws BadLocationException {
        AbstractDocument doc = (AbstractDocument) area.getDocument();
        CompoundEdit group = new CompoundEdit();
        UndoableEditListener collector = e -> group.addEdit(e.getEdit());
        doc.removeUndoableEditListener(undo);
        doc.addUndoableEditListener(collector);
        try {
            doc.replace(0, doc.getLength(), newText, null);
        } finally {
            group.end();
            doc.removeUndoableEditListener(collector);
            doc.addUndoableEditListener(undo);
        }
        undo.addEdit(group);
    }

    private void newFile() {
        if (confirmDiscard()) {
            file = null;
            area.setText("");
            undo.discardAllEdits();
            setModified(false);
        }
    }

    private void open() {
        if (!confirmDiscard()) {
            return;
        }
        JFileChooser chooser = new JFileChooser();
        if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION) {
            return;
        }
        Path path = chooser.getSelectedFile().toPath();
        try {
            TextFile opened;
            try {
                opened = TextFile.open(path);
            } catch (CharacterCodingException e) {
                opened = TextFile.open(path, StandardCharsets.ISO_8859_1);
                status.setText("Not valid UTF-8; opened as ISO-8859-1");
            }
            file = opened;
            area.setText(opened.text());
            area.setCaretPosition(0);
            undo.discardAllEdits();
            setModified(false);
        } catch (IOException e) {
            error("Could not open " + path.getFileName(), e);
        }
    }

    private void save() {
        if (file == null) {
            saveAs();
            return;
        }
        try {
            file = file.withText(area.getText());
            file.save();
            setModified(false);
        } catch (IOException e) {
            error("Could not save " + file.path().getFileName(), e);
        }
    }

    private void saveAs() {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION) {
            return;
        }
        Path path = chooser.getSelectedFile().toPath();
        file = new TextFile(path, area.getText(), StandardCharsets.UTF_8, System.lineSeparator(), false);
        save();
    }

    /** True if there are no unsaved changes, or the user agrees to lose them. */
    private boolean confirmDiscard() {
        if (!modified) {
            return true;
        }
        int answer = JOptionPane.showConfirmDialog(frame, "Save changes to " + displayName() + "?",
            "Unsaved changes", JOptionPane.YES_NO_CANCEL_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            save();
            return !modified;                             // false if saving failed or was cancelled
        }
        return answer == JOptionPane.NO_OPTION;
    }

    private void setModified(boolean value) {
        modified = value;
        updateTitle();
    }

    private String displayName() {
        return file == null ? "Untitled" : file.path().getFileName().toString();
    }

    private void updateTitle() {
        frame.setTitle((modified ? "*" : "") + displayName() + " - Editor");
    }

    private void updateStatus() {
        try {
            int caret = area.getCaretPosition();
            int line = area.getLineOfOffset(caret);
            int column = caret - area.getLineStartOffset(line);
            status.setText("Line " + (line + 1) + ", column " + (column + 1)
                + (file == null ? "" : "   " + file.describe()));
        } catch (BadLocationException e) {
            status.setText(" ");
        }
    }

    private void error(String message, Exception e) {
        JOptionPane.showMessageDialog(frame, message + ":\n" + e.getMessage(), "Error",
            JOptionPane.ERROR_MESSAGE);
    }
}

// Paste SearchOptions, Match, ReplaceResult and Finder (Stage 3)
// and TextFile (Stage 4) here.

The parts that make it feel like a real application:

  • Menu accelerators use the platform's shortcut key. getMenuShortcutKeyMaskEx() is Ctrl on Windows and Linux and Cmd on macOS, so Ctrl+S becomes Cmd+S on a Mac with no extra code.
  • Closing asks about unsaved changes. DO_NOTHING_ON_CLOSE stops the window from closing on its own; the WindowListener asks first. confirmDiscard is shared by New, Open and closing, and choosing Yes saves first, returning false if saving failed so no work is lost.
  • The status bar follows the caret. A CaretListener updates the line and column on every move, using JTextArea.getLineOfOffset, which reads the same line elements as the runnable example.
  • Errors go to the user, not the console. File errors open a dialog; search errors (including bad regexes) appear in the status bar, because a typo in the find field shouldn't interrupt typing with a popup.
  • Everything runs on the event dispatch thread. invokeLater builds the window there, and all listeners run there, so no locks are needed. For very large files, reading on the EDT would freeze the window; that's when you'd move loading into a SwingWorker (see Swing Events).

One simplification remains: this window uses a plain modified flag, so undoing back to the saved text still shows *. Bringing Stage 2's save-point idea to Swing means remembering which UndoableEdit was last when you saved, a good first extension.

Ideas to extend it

  • Save points in Swing. Track the edit at the top of the UndoManager when saving (subclass it to expose editToBeUndone()), and clear the * when the user undoes back to it.
  • Replace one at a time. Add a "Replace" button that replaces the current selection if it matches and then finds the next match.
  • Recent files. Keep the last five paths in a properties file in the user's home directory (see Properties and Configuration) and list them in the File menu.
  • Line numbers. Put a component that paints line numbers in the scroll pane's row header with setRowHeaderView.
  • Word wrap and font size. Add View menu items that call setLineWrap, setWrapStyleWord and setFont with a bigger size.
  • Tests. The document, history, finder and file layers are plain classes: cover the edge cases with JUnit, especially offsets at the very start and end of the text.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the 1-based line and column of offset 6 in the text "ab\ncd\nef"?

    Offsets 0-2 are "a", "b" and the first line break; 3-5 are "c", "d" and the second break. Offset 6 is "e", the first character of line 3.
  2. 2. In plain-text mode, a user replaces price with $5. Why does the Finder pass the replacement through Matcher.quoteReplacement?

    appendReplacement and replaceAll treat $ and backslash specially. quoteReplacement escapes them so the text is inserted literally. Pattern.quote does the same job for the search text.
  3. 3. After saving, the user makes two edits and then presses Undo twice. Why does the Stage 2 document report that it's not modified?

    Modified is computed by comparing the current top of the undo stack with the save point. Undoing back to that point makes them the same object again.
  4. 4. Why does the editor write a temporary file and then move it over the original when saving?

    The original is only replaced by a complete file, in one step where the file system supports atomic moves. The temporary file is created in the same folder because atomic moves can't cross file systems.
  5. 5. Without the CompoundEdit, how many times would the user press Undo to reverse a Replace All implemented with doc.replace(0, length, newText, null)?

    The document records a removal and an insertion as two separate undoable edits. Undoing the insertion first leaves the document empty. Grouping both into a CompoundEdit makes it one step.

Summary

  • The document stores text in a StringBuilder with \n line breaks, validates every range, and converts between 0-based offsets and 1-based lines and columns in one place.
  • Undo/redo uses the command pattern: Insert, Delete and Replace records under a sealed interface, two ArrayDeque stacks, merged typing, and a save point that makes "modified" exact.
  • Find and replace compiles every option into one regex: Pattern.quote for plain text, \b(?:...)\b for whole words, CASE_INSENSITIVE | UNICODE_CASE, and Matcher.quoteReplacement for literal replacements.
  • TextFile reads strictly (bad bytes throw instead of corrupting), keeps the charset, BOM and line separator, and saves through a temporary file and an atomic move.
  • In Swing, JTextArea's PlainDocument is the model, an UndoManager records edits, a CompoundEdit makes Replace All one step, and listeners drive the title and status bar, all on the event dispatch thread.

Next: Project: Multi-Client Chat Server, where you'll build a TCP chat server with a virtual thread per client, nicknames, commands and broadcasting.