1
\$\begingroup\$
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextEditor extends JFrame{

    private JTextArea area = new JTextArea(20,120);
    private JFileChooser dialog = new JFileChooser(System.getProperty("user.home"));
    private String currentFile = "Untitled";
    private boolean changed = false;

    public TextEditor(){

        area.setFont(new Font("Monospaced", Font.PLAIN, 12));
        JScrollPane scroll = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        add(scroll, BorderLayout.CENTER);

        // ====================================== 2 Dropdown lists ==========================================
        // Set 'File' and 'Edit' options to the top of the toolbar
        JMenuBar JMB = new JMenuBar();
        setJMenuBar(JMB);
        JMenu file = new JMenu("File");
        JMenu edit = new JMenu("Edit");
        JMB.add(file); JMB.add(edit);

        // Add Actions to the options in the File dropdown menu
        file.add(New); file.add(Open); file.add(Save); file.add(Quit);

        // Add Actions to the options in the Edit dropdown menu
        edit.add(Cut); edit.add(Copy); edit.add(Paste);
        edit.getItem(0).setText("Cut");
        edit.getItem(1).setText("Copy");
        edit.getItem(2).setText("Paste");
        // ================================================================================

        // ====================================== Icon panel ==========================================
        // Make a toolbar of only the icons
        JToolBar tool = new JToolBar();
        add(tool, BorderLayout.NORTH);

        // Add the New, Open, and Save Actions
        tool.add(New); tool.addSeparator(); tool.add(Open); tool.addSeparator(); tool.add(Save); tool.addSeparator();

        // Create JButtons for Cut Copy, and Paste Actions
        JButton cut = tool.add(Cut); tool.addSeparator();
        JButton cop = tool.add(Copy); tool.addSeparator();
        JButton pas = tool.add(Paste);

        // Add icons and no text to the above JButtons
        cut.setText(null); cut.setIcon(new ImageIcon("src/cut.png"));
        cop.setText(null); cop.setIcon(new ImageIcon("src/copy.png"));
        pas.setText(null); pas.setIcon(new ImageIcon("src/paste.png"));
        // ================================================================================

        // When first create the file set the Save and SaveAs to false
        Save.setEnabled(false);

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Set the window to the smallest possible size
        pack();

        // Listen to any key presses
        area.addKeyListener(listener);
        setTitle(currentFile);
        setVisible(true);
    }

    /**
     * Waits for any key press to allow the user to Save and SaveAs
     */
    private KeyListener listener = new KeyAdapter() {
        public void keyPressed(KeyEvent e) {

            // A change in the file has occurred
            changed = true;
            Save.setEnabled(true);
        }
    };

    /**
     * Select a file from some directory
     */
    Action Open = new AbstractAction("Open", new ImageIcon("src/open.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Activating the Open Action");

            saveOld();
            if(dialog.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
                readInFile(dialog.getSelectedFile().getAbsolutePath());
            }
            Save.setEnabled(true);
        }
    };

    /**
     * Create a new file
     */
    Action New = new AbstractAction("New", new ImageIcon("src/new.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Activating the New Action");

            new TextEditor();
        }
    };

    /**
     * Save the file you were working on
     */
    Action Save = new AbstractAction("Save", new ImageIcon("src/tool.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Activating the Save Action");

            saveFileAs();
        }
    };

    /**
     * Quit the program
     */
    Action Quit = new AbstractAction("Quit") {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Activating the Quit function");

            // Give a user the option to save before quitting
            saveOld();
            System.exit(0);
        }
    };

    /**
     * Set Cut, Copy, and Paste to default Actions provided by the JVM
     */
    ActionMap m = area.getActionMap();
    Action Cut = m.get(DefaultEditorKit.cutAction);
    Action Copy = m.get(DefaultEditorKit.copyAction);
    Action Paste = m.get(DefaultEditorKit.pasteAction);

    /**
     * Save the file
     */
    private void saveFileAs(){
        if(dialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
            saveFile(dialog.getSelectedFile().getAbsolutePath());
    }

    /**
     * Give the user a pop-up window with option of saving or not saving the file
     */
    private void saveOld(){
        if(changed){
            if(JOptionPane.showConfirmDialog(this, "Would you like to save "+currentFile+" ?", "Save", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                saveFile(currentFile);
        }
    }

    /**
     * Reads the file into the program
     * @param fileName The file to be read in
     */
    private void readInFile(String fileName){
        try{
            FileReader r = new FileReader(fileName);
            area.read(r, null);
            r.close();

            currentFile = fileName;
            setTitle(currentFile);
            changed = false;

        }catch (IOException e){
            JOptionPane.showMessageDialog(this, "Editor can't find the file called "+fileName);
        }
    }

    /**
     * Save the file
     * @param fileName a custom name for the file to be saved
     */
    private void saveFile(String fileName){
        try{
            FileWriter w = new FileWriter(fileName);
            area.write(w);
            w.close();

            currentFile = fileName;
            setTitle(currentFile);
            changed = false;
            Save.setEnabled(false);

        }catch(IOException e){}
    }

    public static void main(String[] args){
        new TextEditor();
    }

}

The class and the program itself works fine. Except for the New file feature. When I click the New file button it does open a new window, BUT when I close the new opened window it closes ALL the windows.

The problem is in this line of code setDefaultCloseOperation(EXIT_ON_CLOSE);, because it closes all the windows at ones.

I have found the same post Similar Post, but because I'm new to programming I didn't really understands what the answer meant :

separate your window code from your application instance your application instance should manage its open windows. A window should inform the application instance when it is closed and the application should exit when its last window is closed.

It seems like he is suggesting to use an MVC model, but I'm still confused on how the window should inform the application that it is closed...

\$\endgroup\$
  • 2
    \$\begingroup\$ Broken code (closes all windows instead of just one) is off-topic here. But there is plenty of other code to review which is on topic. \$\endgroup\$ – Sjoerd Job Postmus May 12 '16 at 6:39
  • \$\begingroup\$ Can you point out some other bad code ? \$\endgroup\$ – user98627 May 12 '16 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy