next up previous
Next: Now lets Swing Up: On from AWT Previous: On from AWT

A simple AWT program

Let us look at a simple AWT program that contains a toolbar and 3 Buttons.

It produces output like this:

Simple AWT Program Output

The full code listing is as follows:

/*
 * ToolbarFrame1.java
 * A simple frame containing a "toolbar" made up of several java.awt.Button
 * objects.  We'll be converting the Buttons to JButtons in the
 * ToolbarFrame2.java file.
 */

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

public class ToolbarFrame1 extends Frame implements ActionListener {

  Button cutButton, copyButton, pasteButton;
  public ToolbarFrame1() {
    super("Toolbar Example (AWT)");
    setSize(450, 250);
    addWindowListener(new BasicWindowMonitor());
  
    Panel toolbar = new Panel();
    toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));

    cutButton = new Button("Cut");
    cutButton.addActionListener(this);
    toolbar.add(cutButton);

    copyButton = new Button("Copy");
    copyButton.addActionListener(this);
    toolbar.add(copyButton);

    pasteButton = new Button("Paste");
    pasteButton.addActionListener(this);
    toolbar.add(pasteButton);

    add(toolbar, BorderLayout.NORTH);
  }

  public void actionPerformed(ActionEvent ae) {
    System.out.println(ae.getActionCommand());
  }

  public static void main(String args[]) {
    ToolbarFrame1 tf1 = new ToolbarFrame1();
    tf1.setVisible(true);
  }
}

The BasicWindowMonitor Class is also needed and is frequently used in other later examples:

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

public class BasicWindowMonitor extends WindowAdapter {

  public void windowClosing(WindowEvent e) {
    Window w = e.getWindow();
    w.setVisible(false);
    w.dispose();
    System.exit(0);
  }
}



Dave Marshall
4/14/1999