// MyFrameWithExitHandling.java: Define a new frame with exit
// capability and the center() method
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class MyFrameWithExitHandling extends JFrame
  implements WindowListener
{
  // Main method
  public static void main(String[] args)
  {
    MyFrameWithExitHandling frame =
      new MyFrameWithExitHandling("Test Frame");
    frame.setSize(200, 200);
    frame.center();
    frame.setVisible(true);
  }

  // Default constructor
  public MyFrameWithExitHandling()
  {
    super();
    addWindowListener(this);  // Register listener
  }

  // Constructor a frame with a title
  public MyFrameWithExitHandling(String title)
  {
    super(title);
    addWindowListener(this); // Register listener
  }

  // Center the frame
  public void center()
  {
    // Get the screen dimension
    Dimension screenSize =
      Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;

    // Get the frame dimension
    Dimension frameSize = this.getSize();
    int x = (screenWidth - frameSize.width)/2;
    int y = (screenHeight - frameSize.height)/2;

    // Determine the location of the left corner of the frame
    if (x < 0)
    {
      x = 0;
      frameSize.width = screenWidth;
    }

    if (y < 0)
    {
      y = 0;
      frameSize.height = screenHeight;
    }

    // Set the frame to the specified location
    this.setLocation(x, y);
  }

  // Handler for window closed event
  public void windowClosed(WindowEvent event)
  {
  }

  // Handler for window deiconified event
  public void windowDeiconified(WindowEvent event)
  {
  }

  // Handler for window iconified event
  public void windowIconified(WindowEvent event)
  {
  }

  // Handler for window activated event
  public void windowActivated(WindowEvent event)
  {
  }

  // Handler for window deactivated event
  public void windowDeactivated(WindowEvent event)
  {
  }

  // Handler for window opened event
  public void windowOpened(WindowEvent event)
  {
  }

  // Handler for window closing event
  public void windowClosing(WindowEvent event)
  {
    dispose();
    System.exit(0);
  }
}

