WindowListener is interface
which force you to override
all of the methods, while WindowAdapter is implementation of WindowListener
and you only need to override
the method(s) that you interest to deal with.
看板 ott
作者 標題 What is the difference between listeners and adapters?
時間 2013年01月21日 Mon. AM 05:37:30
I'm trying to differentiate between listeners and adapters.
Are they pretty much the same but in listeners you have to implement all the methods in the interface, but with adapters you have an option to only implement the methods you need so the code is cleaners and easier to read?
I also got told that adapters enable instantiation with only one implementation and you can't instantiate listeners, I don't fully understand this.
https://disp.cc/b/Stupid&ti=4dlA#!158-1xvw
Can someone please explain which one is better to use and things you can do with one but you can't with the other?
WindowListener
is interface which mean you cant instantiation the WindowListener
, while WindowAdapter
is concrete class that you can use new
operator to instantiation.
When you use WindowAdapter
, the code is more clean where your class only override the method(s) that you want.
For example:
WindowListener
public class CloseListener implements WindowListener {
// im not interest on this event, but still need to override it
@Override
public void windowOpened(WindowEvent e) {
}
// im not interest on this event, but still need to override it
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
System.exit(0);
}
// im not interest on this event, but still need to override it
@Override
public void windowIconified(WindowEvent e) {
}
// im not interest on this event, but still need to override it
@Override
public void windowDeiconified(WindowEvent e) {
}
}
WindowAdapter
While using adapter the code is cleaner:
// at JFrame class
addWindowListener(new CloseListener());
// reusable Close Listener
public class CloseListener extends WindowAdapter {
@Override
public void windowClosed(WindowEvent e) {
System.exit(0);
}
}
Or
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
So I would recommend to use WindowAdapter
, but not must follow. However, two of the API about the same just that WindowAdapter
exists as convenience for creating listener objects.
EDIT:
Since WindowListener
is interface
, you can implement it at your JFrame subclass.
public class MainWindow extends JFrame implements WindowListener {
// this is ok
}
public class MainWindow extends JFrame, WindowAdapter {
// this is not allow
}
But you cant do it with WindowAdapter
.
※ 編輯: ott 時間: 2013-01-22 06:55:33
※ 看板: ott 文章推薦值: 0 目前人氣: 0 累積人氣: 80
回列表(←)
分享