11.4 Creating a Frame 

Previous Index Next 


A Frame object represents a window in a Java GUI application. To create a window you must extend the Frame class. The following code shows an example:
import java.awt.*;       // import java gui classes
import java.awt.event.*;

public class TestFrame extends Frame
 {
  // Constructor for frame. This method does the following:
  // 1) Initializes the frame by calling it's ancestors constructor
  // 2) Sets the window to be 640 x 480 pixels wide
  // 3) Creates a window listener and adds it to the frame.
  public TestFrame()
   {
    super("This is the Windows Title");
 
    setBounds(0,0,640,480);
 
    addWindowListener( new FrameWindowListener() );
   }
 
  // This inner class handles window events.
  // It provides code for the window closing event which
  // ends the execution of the application.
  class FrameWindowListener extends WindowAdapter
   {
    public void windowClosing(WindowEvent e)
     {
      System.exit(0);
     }
   }

  // void main method of the application.
  // It creates an instance of the frame and then shows it.
  public static void main(String[] args)
   {
    TestFrame mainWindow = new TestFrame();
 
    mainWindow.show();
   }
 }
In the code above not the use of an inner class to provide the code for handling the closing of the window. The default behavior for the closing of a window is to simply hide the window. By providing a WindowListener we can force the termination of the application when the window is closed.