Home : Course Map : Chapter 7 : Java :
Menus & Frames
JavaTech
Course Map
Chapter 7

Introduction
Event Overview
Event Processing
Button Events
  Demo 1
 Demo 2
Mouse Events
  Demo3

More Components
  Demo 4  Demo 5
  Demo 6  Demo 7

LayoutManagers-1
  Demo 8     Demo 9
  Demo 10  Demo 11
  Demo 12

LayoutManagers-2
  Demo 13  Demo 14
  Demo 15  Demo 16
  Demo 17

Inner Classes
Anonymous Class
Adapter Classes
  Demo 18  Demo 19
Frames & Menus
  Demo 20  Demo 21
Exercises

    Supplements
AWT Components
  Button
     Demo 1
  Canvas
     Demo 2
  AWT GUI Demo
     Demo 3
Swing Dialogs
JOptionPane Dialog
  Demo 1
JDialog
  Demo 2
UI Enhancement: P1
  Demo 1   Demo 2
  Demo 3

UI Enhancement: P2
  Demo 1
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The two examples here illustrate the use of menu bars, drop down menus, and window frames for program graphical interfaces.

  1. Frame & Menus for an Applet - the first example shows how to put menu bars on an applet in the browser window and also to open a frame above the browser.
  2. Applet/Application Option - the second example shows how to create a GUI program that can run either as an applet or in a standalone application window.

Frame & Menus for Applet

One nice advantage of the Swing applets is that a menu bar can now be added to the panel on the browser page. Previously, the heavyweight menu bar component could not be put onto the browser. The lightweight Swing menus are simply drawn on the panel like any other Swing component.

The only way in the basic AWT to obtain a menu bar is to open a frame, or window, outside of the browser, similar to a dialog (we will discuss dialog components in the Chapter 7: Supplements section ).

The following applet illustrates both techniques. The browser applet panel uses a menu bar to hold a drop down menus. From the menu you can choose to open up a frame, which holds its own menu bar and some other components.

The example illustrates the basics of creating a menu bar, menu items, and dropdown menus. Also, it includes a combobox compoent that holds a list of options, only one of which can be chosen

FrameApplet.java
   

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
  * This program demonstrates the basics of creating a frame
  * user interface with a menubar. It also shows how to
  * add a menubar and dropdown menus to the applet, which wasn't
  * possible in the basic AWT heavyweight component.
 **/
public class FrameApplet extends JApplet
       implements ActionListener
{
  JFrame fFrame;
  JMenuItem fMenuClose ;
  JMenuItem fMenuOpen;

  /** Build an applet interface with a menubar. A
    * a drop down menu includes Open/Close items
    * for opening and closing an instance of ParticleFrame.
   **/
  public void init () {
    JMenuBar mb = new JMenuBar ();
    JMenu m = new JMenu ("File");
    fMenuOpen= new JMenuItem ("Open");
    m.add (fMenuOpen);
    fMenuOpen.addActionListener (this);

    fMenuClose = new JMenuItem ("Close");
    m.add (fMenuClose);
    fMenuClose.addActionListener (this);
    mb.add (m);

    setJMenuBar (mb);

    fFrame = new ParticleFrame (this);
    fFrame.setVisible (true);
    fMenuOpen.setEnabled (false);
    fMenuClose.setEnabled (true);

  } // init

  /** Get the menu events here. Open an instance of ParticleFrame
    * or close the one currently displayed.
   **/
  public void actionPerformed (ActionEvent e) {
    String command = e.getActionCommand ();
    if (command.equals ("Close")) {
        close ();
    } else { // Open
        if (fFrame == null) {
            fFrame = new ParticleFrame (this);
            fFrame.setVisible (true);
            fMenuOpen.setEnabled (false);
            fMenuClose.setEnabled (true);
        }
    }
  } // actionPerformed

  /** Close the frame. **/
  void close () {
    fFrame.dispose ();
    fFrame = null;
    fMenuOpen.setEnabled (true);
    fMenuClose.setEnabled (false);
  } // close

} // class FrameApplet


/** A JFrame subclass that displays a menu bar
  * and a JComboBox.
 **/
class ParticleFrame extends JFrame
                    implements ActionListener, ItemListener
{
  JLabel fLabelA;
  JLabel fLabelB;

  FrameApplet fApplet;

  ParticleFrame (FrameApplet applet) {
    super ("Frame Test");

    fApplet = applet;
    Container content_pane = getContentPane ();

    content_pane.setLayout (new GridLayout (1,3));

    JPanel choice_panel = new JPanel ();
    choice_panel.add (new JLabel ("Quark", JLabel.RIGHT) );

    JComboBox c = new JComboBox ();
    c.addItem ("Up");
    c.addItem ("Down");
    c.addItem ("Strange");
    c.addItem ("Charm");
    c.addItem ("Top");
    c.addItem ("Bottom");
    c.addItemListener (this);
    choice_panel.add (c);

    content_pane.add (choice_panel);

    fLabelA =new JLabel ("Quark: Up");
    content_pane.add (fLabelA);
    fLabelB =new JLabel ("Lepton: Electron");
    content_pane.add (fLabelB);

    // Use the helper method makeMenuItem
    // for making the menu items and registering
    // their listener.
    JMenu m = new JMenu ("Lepton");
    m.add (makeMenuItem ("electron"));
    m.add (makeMenuItem ("muon"));
    m.add (makeMenuItem ("tau"));

    JMenu sm = new JMenu ("Neutrino");
    sm.add (makeMenuItem ("e Neutrino"));
    sm.add (makeMenuItem ("mu Neutrino"));
    sm.add (makeMenuItem ("tau Neutrino"));

    m.add (sm);
    m.add (makeMenuItem ("Quit"));
    JMenuBar mb = new JMenuBar ();
    mb.add (m);

    setJMenuBar (mb);
    setSize (200,200);
    pack ();
    setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
  } // ctor

  /** Get the combobox item events here. **/
  public void itemStateChanged (ItemEvent e) {
    String command = e.getItem ().toString ();
    if (command.equals ("Quit") )
        dispose ();
    else
        fLabelA.setText ("Quark: " + command);
  } // itemStateChanged

  /** Get the menu events here. **/
  public void actionPerformed (ActionEvent e) {
    String command = e.getActionCommand ();
    if (command.equals ("Quit")) {
        fApplet.close ();
    } else {
        fLabelB.setText ("Lepton: " + command);
    }
  } // actionPerformed

  /** This "helper method" makes a menu item and then
    * registers this applet as a listener to it.
   **/
  private JMenuItem makeMenuItem (String name) {
    JMenuItem m = new JMenuItem (name);
    m.addActionListener (this);
    return m;
  } // makeMenuItem

} // class ParticleFrame

 

Applet / Application Option

The following example shows how to create a GUI program that runs either as an applet or as a standalone frame. A panel class is added either to the applet's panel or to the frame.

FrameAppApplet.java  
import javax.swing.*;
import java.awt.*;

/**
  * This program can run either as an applet or an application.
  * Both display an image on a JPanel object.
 **/
public class FrameAppApplet extends JApplet{
  static boolean fInBrowser = true;

  /** Create the applet interface by adding a DrawingPanel,
    * which will display an image.
   **/
  public void init ()  {
    Container content_pane = getContentPane ();

    // Grab the image with appropriate method.
    Image img;
    if (fInBrowser)
        img = getImage (getCodeBase (), "Apollo16Lander.jpg");
    else
        img = Toolkit.getDefaultToolkit ().getImage (
                                       "Apollo16Lander.jpg");

    // Create an instance of DrawingPanel
    DrawingPanel drawing_panel = new DrawingPanel (img);

    // Add the DrawingPanel to the content_pane.
    content_pane.add (drawing_panel);

  } // init

  /** For standalone mode, create a JFrame and add an instance
    * of this applet to it.
   **/
  public static void main (String[] args) {
    // Running as an application
    fInBrowser = false;
    // Create applet object
    JApplet applet = new FrameAppApplet ();

    // Create Frame
    JFrame f = new JFrame ("Frame/Applet Demo");
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    // Add applet to the frame
    f.getContentPane ().add (applet);
    f.setSize (new Dimension (350,250));

    // Initialize the applet
    applet.init ();
    f.setVisible (true);
  } // main

} // class FrameAppApplet

/** Draw on a JPanel rather than on JApplet's Panel. **/
class DrawingPanel extends JPanel
{
  Image fImg = null;

  DrawingPanel (Image img) {
    fImg = img;
  } // ctor

  /** Display an image. **/
  public void paintComponent (Graphics g) {
    // First paint background
    super.paintComponent (g);

    // Use the image width& width to find the starting point
    int img_x = getSize ().width/2  - fImg.getWidth (this)/2;
    int img_y = getSize ().height/2 - fImg.getHeight (this)/2;

    //Draw image at centered in the middle of the panel
    g.drawImage (fImg, img_x, img_y, this);

  } // paintComponent

} // class DrawingPanel

 

Note that to allow for closing the frame by clicking on the usual closing button on the top window bar, you implement the JFrame method:

  setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

This command is not available for the Frame class in the AWT. Instead, the following, which is a nice example of using an adapter class, creates an instance of WindowAdapter to provide this closing service wiht an overriden windowClosing() method.

    // Following anonymous class used to close
    // window & exit program
    Frame f = new Frame("Frame & Image Demo");
    f.addWindowListener

    ( new
WindowAdapter()
     {

       public void windowClosing
(WindowEvent e) {
         System.exit
(0);
       
}
     }
    )
;

References & Web Resources

You can find more info about the JMenubar, JMenu, JMenuItem, and JFrame classes in the API Specifications and in the the following Sun Java Tutorial sections:

 

Latest update: Nov. 4, 2004

           Tech
Histogram UI
  Demo 1
Probablity Distrib.
  Demo 2 Demo 3
RejectionMethod
Histogram Stats
  Demo 4
Exercises

           Physics
Sim & Randomness
Custom Prob. Dist.
   Demo 1
Histogram Dist.
   Demo 2
Monte Carlo
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.