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?
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
Yes, you have to implement all methods.
This is how interfaces work: they define a contract that implementors must follow. If that contract consists of 5 methods then you have to implement all 5 of them.
When there is a consequent number of methods, the Adapter design-pattern is usually put in place: an abstract class that provides default implementation that do nothing is created.
For the WindowListener
interface, this is WindowAdapter
. So, instead of implementing WindowListener
(and all of its methods), you can just extend WindowAdapter
and override only the methods you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With