Aqua Phoenix
     >>  Lectures >>  Java 5  
 

Navigator
   
 
       
   

5.2 Template

Java Applications use JFrame as their GUI foundation. JFrames can be considered equivalent to the main window of MS Word, Netscape, Notepad, or any other GUI applications. While Java applets extended the object Applet, Java applications extend JFrame.

JFrames are very versatile and can be used to create two different styles of applications:

  • Single Window: use JFrame and fill its main container with JPanels and other GUI widgets
  • Multiple Windows: use JFrame and fill its main window with another container that supports JInternalFrames, which are JFrames within a JFrame

The following is a template of a typical one-window Java application:

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

public class JavaApplication extends JFrame {

  public JavaApplication() {

    super("Java Application");

    setSize(800, 600);

    Container content = getContentPane();

    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    setVisible(true);
  }

  public static void main(String[] args) {

    JavaApplication javaApplication = new JavaApplication();
  }
}
In the constructor for any Java applications, the size of the frame must be set explicitely, and a WindowListener must be added to listen to the close command. Without the WindowListener, the JFrame will not close when clicking on the window's close button.

getContentPane() is used to obtain the main container of the JFrame. It can be used to add JPanels, menus, and other GUI widgets to the window.