zoukankan      html  css  js  c++  java
  • Java基础之处理事件——使用适配器类(Sketcher 3 using an Adapter class)

    控制台程序。

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

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

     1 // Sketching application
     2 import javax.swing.*;
     3 import java.awt.*;
     4 import java.awt.event.*;
     5 
     6 public class Sketcher {
     7   public static void main(String[] args) {
     8      theApp = new Sketcher();                                          // Create the application object
     9    SwingUtilities.invokeLater(new Runnable() {
    10             public void run() {
    11               theApp.createGUI();                                      // Call GUI creator
    12             }
    13         });
    14   }
    15 
    16   // Method to create the application GUI
    17   private void createGUI() {
    18     window = new SketcherFrame("Sketcher");                            // Create the app window
    19     Toolkit theKit = window.getToolkit();                              // Get the window toolkit
    20     Dimension wndSize = theKit.getScreenSize();                        // Get screen size
    21 
    22     // Set the position to screen center & size to half screen size
    23     window.setSize(wndSize.width/2, wndSize.height/2);                 // Set window size
    24     window.setLocationRelativeTo(null);                                // Center window
    25 
    26     window.addWindowListener(new WindowHandler());                     // Add window listener
    27     window.setVisible(true);
    28   }
    29 
    30   // Handler class for window events
    31   class WindowHandler extends WindowAdapter {
    32     // Handler for window closing event
    33     @Override
    34     public void windowClosing(WindowEvent e) {
    35       window.dispose();                                                // Release the window resources
    36       System.exit(0);                                                  // End the application
    37     }
    38   }
    39 
    40   private SketcherFrame window;                                        // The application window
    41   private static Sketcher theApp;                                      // The application object
    42 }

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

  • 相关阅读:
    Oracle之内存结构(SGA、PGA)
    学员报名WDP培训之前必须阅读
    常见滤波方法
    C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?
    C++ explicit关键字详解
    A、B、C、D和E类IP地址
    BOOL和bool的区别
    互斥量 临界区 信号量 条件变量 效率对比
    Unhandled exception at 0x........ in XXXX.exe: 0xC0000005:错误
    链表的插入操作错误
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3486115.html
Copyright © 2011-2022 走看看