Buttons are instances of the java.awt.Button class, a subclass of java.awt.Component. Buttons are created with the Button(String label) constructor. This creates a new button with the label printed on it. Then you add the button to the layout. For example,

  Button b; 
  b = new Button("My First Button");

If this looks familiar it should. It's almost identical to the syntax for creating a new label. You'll use this syntax over and over again for all the different user interface components including text fields, text areas, scrollbars, canvases and more. The only thing that changes is the constructor.

The shortcut is the same also. The three lines are often combined into the single line

this.add(new Button("My First Button"));

Here's a very simple applet with a Button:

Button in an applet

import java.applet.*;
import java.awt.*;

public class FirstButton extends Applet {
   public void init () {
     this.add(new Button("My First Button"));


Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified November 4, 1997