javaswingintellij-ideajframe

Code won't run if super.windowClosing(e) doesn't exist, and it requires a ";", which causes the IDE to treat it as if it was not there


This is my first question on here, so any feedback about the way I asked this question would be helpful.

I am writing code that will save information to a text file when the JFrame gets closed. When I initially wrote the listener, Intellij put in that extra line of code (super.windowClosing(e)) because there was an error initially (Cannot resolve method 'add(WindowAdapter)'), so I had pressed the fix button which put in that line, but it also caused an error to pop up saying that it was missing a semicolon.

//Thread 4

Thread t4 = new Thread(() -> frame.add(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e)  \* ; */ {

                    try {
                        FileWriter writer = new FileWriter("Registry.txt");

                        for (String key : loginRegistry.keySet()) {
                            //write key to file
                            for (String innerKey : loginRegistry.get(key).keySet()) {
                                //write innerKey to file
                                //write get(innerKey) to file
                            }
                        }
                        writer.close();
                        frame.dispose();
                        System.exit(0);

                    }catch(IOException x){x.printStackTrace();}

                    }
                }

        }));

This code segment is supposed to write down a map (containing strings and maps(containing a string and a char array)) into a file, so that when the program is run again it can read the information that was saved. But the program won't run do to the error.


Solution

  • frame.add(new WindowAdapter() is an invalid call, as JFrame does not have a add(WindowListener) method and instead, you should be using the JFrame#addWindowListener method, for example...

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.out.println("Window is closing");
        }
    });
    

    Swing is also NOT thread safe.

    Thread t4 = new Thread(() -> frame.add(new WindowAdapter() { ... })
    

    is violating this rule and doesn't make a lot of sense.

    This will cause the Thread to call the add method of the JFrame, but the call to windowClosing will be executed within the context of the Event Dispatching Thread ... so it just seems completely pointless.

    You should take a closer look at Concurrency in Swing