控制台程序。

适配器类是指实现了监听器接口的类,但监听器接口中的方法没有内容,所以它们什么也不做。背后的思想是:允许从提供的适配器类派生自己的监听器类,之后再实现那些自己感兴趣的类。其他的空方法会从适配器类中继承,所以无须担心它们。

修改上一文中的Sketcher类如下:

 // Sketching application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the application object
SwingUtilities.invokeLater(new Runnable() {
public void run() {
theApp.createGUI(); // Call GUI creator
}
});
} // Method to create the application GUI
private void createGUI() {
window = new SketcherFrame("Sketcher"); // Create the app window
Toolkit theKit = window.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size // Set the position to screen center & size to half screen size
window.setSize(wndSize.width/2, wndSize.height/2); // Set window size
window.setLocationRelativeTo(null); // Center window window.addWindowListener(new WindowHandler()); // Add window listener
window.setVisible(true);
} // Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
@Override
public void windowClosing(WindowEvent e) {
window.dispose(); // Release the window resources
System.exit(0); // End the application
}
} private SketcherFrame window; // The application window
private static Sketcher theApp; // The application object
}

Sketcher类不再是window事件的监听器,所以不需要实现WindowListener接口。WindowHandler类是window事件的监听器类。WindowHandler类是Sketcher类的内部类,可以访问Sketcher类的所有成员,所以调用window对象的dispose()方法时非常简单-只需要访问顶级类的window域即可。

05-11 17:12