Buttons

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");
    this.add(b);
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

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

Here's a very simple applet with a Button:

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


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

}

Previous | Next | Top
Last Modified November 4, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu