Widgets (Components) Example Code
Fall 2002, David Matuszek

Components (also known as widgets) are the various user controls and displays provided by the Java AWT; they are the basic building blocks of a Graphical User Interface. The following illustration shows the most common AWT components:

  • Label
  • Button
  • Checkbox
  • Choice
  • Scrollbar
  • List
  • TextField
  • TextArea
  • CheckboxGroup (containing Checkboxes)

This is a "live" applet, not just a picture of an applet (try it!). Each of the components in the above applet, when manipulated, places a message in the status line of the applet (in the above illustration, the status line contains the text Applet started.) When you run the applet with appletviewer, the status line is shown at the bottom of the applet; when you run the applet in a browser, the status line is usually shown at the bottom of the browser window (although some browsers may not show the status line at all).

The code for this applet illustrates:

  1. Constructing various components,
  2. Adding components to the Applet,
  3. Attaching listeners to each component, and
  4. Writing the listeners.

I recommend that you download the source code for the above applet and keep it handy. When you want to use a particular kind of component, you can use this code as a model for how to create the component and handle the events that it generates.

There are two versions of the source code for this applet:

Widgets.java uses anonymous inner classes; complete BlueJ package is in WidgetsAnonymous.zip.

Widgets2.java uses member classes; complete BlueJ package is in WidgetsMembers.zip.

In general, member classes are easier to understand, while anonymous inner classes are more convenient.

Note: a .jar file is just like a .zip file, and you can use WinZip or equivalent to unpack it.