您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 8

Managing the main window

When the user interacts with the main window, Java sends events. The events can be received by a WindowListener. The main window itself can be a window listener, or another class can take this responsibility. 

There are seven different events, and the listener must handle all of them, even to ignore them. WindowListener is an interface, and specifies seven different methods:

    windowClosing() 

(the most important) which is called when the user clicks on the ‘close’ icon to close the window. In summary, the others are:

    WindowActivated()

The main window has been activated (e.g., raised to the ‘top’ of the display)

    WindowDeactivated()

The main window has been deactivated (e.g., a different window has been raised to the ‘top’ of the display)

    WindowClosed()

The window has been closed (this is different from windowClosing , which indicates an intention to close)

    WindowDeiconified()

The window has been restored from a icon

    WindowIconified()

The window has been shrunk to an icon

    WindowOpened()

The window has been displayed for the first time

To make the main window able to manage itself, that is, receive events from the user interface, it can be defined like this:

class MainWindow extends Frame implements WindowListener

However, MainWindow must now implement all the methods described above, even if they don’t do anything. To enable the receiving of events, the main window’s constructor can have the line:

AddWindowListener (this);

For example the constructor of a class MainWindow might look as follows:

class MainWindow extends Frame implements WindowListener

  {

  public MainWindow()

    {

    // In the constructor we set the size and caption of the

    // window, and specify ‘this’ as the window listener

    super("Do-nothing program");

    setSize(300, 300);

    addWindowListener (this);

  }

  //... other methods

  } // class

An example of a method to be invoked when a windowClosing() message is received would look as follows:

public void windowClosing (WindowEvent e)

  {

  // do actions to terminate application

  }

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg