javaswingwindowlistener

Do you have to add unimplemented methods?


I am trying to add a listener to a JFrame closing operation:

addWindowListener(new WindowListener() {
    @Override
    public void windowClosing(WindowEvent e) {
        setVisible(false);
    }
});

The thing is that Eclipse keeps telling me I have to "add unimplemented methods", which I assume it gets from the WindowListener. I am confused, though, as to why you need to implement all these other methods as well, if you only need to override one? And if I do add all those other methods, but don't put any content in them e.g.

@Override
public void windowActivated(WindowEvent e) {}

will the default behaviour for this method get lost? Or will it only get overriden if I write something inside the method?


Solution

  • If you implement an interface you must implement all methods. That also applies for anonymous classes.

    Use WindowAdapter instead of implementing WindowListener

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false);
        }
    });
    

    WindowAdapter is a class that implements WindowListener with empty methods and let you override only the ones you need.

    PS: There are also other adapters for other events in swing. E.g. MouseAdapter, KeyAdapter