Pau*_*Wee 31
WindowListener的是interface它迫使你override所有的方法,而WindowAdapter的是执行的WindowListener,你只需要override在方法(S),你的兴趣来处理.
WindowListener是界面,这意味着你无法实例化WindowListener,而WindowAdapter具体的类你可以使用new运算符来实例化.
当您使用时WindowAdapter,代码更干净,您的类只覆盖您想要的方法.例如:
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
在使用适配器时,代码更清晰:
// at JFrame class
addWindowListener(new CloseListener());
// reusable Close Listener
public class CloseListener extends WindowAdapter {
@Override
public void windowClosed(WindowEvent e) {
System.exit(0);
}
}
Run Code Online (Sandbox Code Playgroud)
要么
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
Run Code Online (Sandbox Code Playgroud)
所以我建议使用WindowAdapter,但不一定要遵循.但是,两个关于相同的API只是WindowAdapter为了创建监听器对象而存在.
编辑:
因为WindowListener就是interface,你可以在你的JFrame的子类中实现它.
public class MainWindow extends JFrame implements WindowListener {
// this is ok
}
public class MainWindow extends JFrame, WindowAdapter {
// this is not allow
}
Run Code Online (Sandbox Code Playgroud)
但你不能这样做WindowAdapter.
你可以用任何一种方法做任何事情,但是如果从界面开始,你的代码就会有很多样板.我确定你注意到了,当你尝试出来的时候.关于实例化等的陈述是一种非常复杂的说法,并且存在很多术语混淆.你可以写
c.addWindowListener(new WindowListener() {
@Override public void windowActivated(WindowEvent arg0) { }
@Override public void windowClosed(WindowEvent arg0) { System.exit(0); }
@Override public void windowClosing(WindowEvent arg0) { }
@Override public void windowDeactivated(WindowEvent arg0) { }
@Override public void windowDeiconified(WindowEvent arg0) { }
@Override public void windowIconified(WindowEvent arg0) { }
@Override public void windowOpened(WindowEvent arg0) { }
});
Run Code Online (Sandbox Code Playgroud)
或者你可以写
c.addWindowListener(new WindowAdapter() {
@Override public void windowClosed(WindowEvent arg0) { System.exit(0); }
});
Run Code Online (Sandbox Code Playgroud)
在两种情况下,你实例要么WindowListener或WindowAdapter-你正在创建匿名类实现WindowListener/扩展WindowAdapter.但是当你直接实现接口时,你被迫实现所有方法,当你扩展适配器类时,你只能覆盖你需要的东西.该类已经具有您必须在该Listener案例中编写的这些空实现.
| 归档时间: |
|
| 查看次数: |
30445 次 |
| 最近记录: |