Saturday, 23 August 2014

How to Close a Java Frame

I wanted to be able to close my Java window by clicking on the x in the top left hand corner. To do this, I added the WindowListener interface as shown below. The window does not look much different (except that it is blue this time) but I can close it now without returning to the UNIX prompt and using Ctrl+C. As usual, click on the image to enlarge it and bring it into focus:

andrew@UBUNTU:~/Java$ cat AndrewsFrame.java
import java.awt.*;
import java.awt.event.*;
public class AndrewsFrame
extends Frame
implements WindowListener
{
public AndrewsFrame()
  {
  super("Andrew's Frame");
  setSize(500,300);
  setBackground(Color.blue);
  setVisible(true);
  addWindowListener(this);
  }
public void windowClosing(WindowEvent x)
  {
  dispose();
  System.exit(0);
  }
public void windowActivated(WindowEvent x) { }
public void windowDeactivated(WindowEvent x) { }
public void windowOpened(WindowEvent x) { }
public void windowClosed(WindowEvent x) { }
public void windowIconified(WindowEvent x) { }
public void windowDeiconified(WindowEvent x) { }
public static void main (String args[])
  {
  AndrewsFrame af = new AndrewsFrame();
  }
}
andrew@UBUNTU:~/Java$ javac AndrewsFrame.java
andrew@UBUNTU:~/Java$ java AndrewsFrame