Before you start using the components, you should know what the Component class will provide
and how can you customize the components. Then will tell how to use the components which the
AWT provides. Each kind of the component has its own page:
A D V E R T I S E M E N T
How to Use the Buttons
The Buttons class do provides a default button implementation. The onscreen appearance of
the Buttons depends on a platform they are running on. If you want the program's buttons
to look same for all platform or otherwise to have a special look, you should
create a Canvas subclass to implement this look; the look can't be changed using the
Button subclass. The only facets of Button's appearance that we can change without
creating our own class are the fonts and text it displays and the foreground and
background colors.
Below is an applet which displays three buttons. When you click the left button, it
disables middle button and enables the right one. Similarly when you on click the
right button, it will enable the left button and the middle button , and it disables
itself. Below is the code which will create the buttons and reacts to the button clicks.
//In initialization code:
b1 = new Button();
b1.setLabel("Disable middle button");
b2 = new Button("Middle button");
b3 = new Button("Enable middle button");
b3.disable();
public boolean handleEvent(Event e)
{
Object target = e.target;
A Canvas class exist to be subclassed. It will not do anything on its own; it merely
provides the way to implement the custom Components. For example, The Canvases are
useful as a display area for images and the custom graphics, whether or not you wish to
handle the events that occurs within a display area.
While implementing a Canvas subclass. do take care to implement the minimumSize() and
the preferredSize() method to properly reflect the canvas's size. Otherwise, depending
on the layout which the canvas's container uses, your canvas could end up too small --
perhaps even be invisible. Here is an example of the Canvas subclass that displays
the image:
The Checkbox class provides the checkboxes -- two-state buttons which can either be "on"
or "off". If we want the group of checkboxes in which only one of the checkbox
can be "on" at a time, you can add the CheckboxGroup object to oversee the checkboxes.
Other good ways of providing a group of items the user can select are the choices,
lists, and menus.
Given below is code for an applet that contains two columns of checkboxes. On the left
are three independent checkboxes. You can select all the three checkboxes, if you like to.
On the right are the three checkboxes which are coordinated by the CheckboxGroup object.
The CheckboxGroup ensures no more than one of its checkboxes is selected at a time.
Here is the program which performs this task. Below is the code that creates both the
groups of checkboxes. Note: only the second, mutually-exclusive group of
checkboxes is controlled by the CheckboxGroup.
Panel p1, p2;
Checkbox cb1, cb2, cb3; //independent checkboxes
Checkbox cb4, cb5, cb6; //only one of these three can be selected
CheckboxGroup cbg;
cb1 = new Checkbox();
cb1.setLabel("Checkbox 1");
cb2 = new Checkbox("Checkbox 2");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true);
. . .
cbg = new CheckboxGroup();
cb4 = new Checkbox("Checkbox 4", cbg, false);
cb5 = new Checkbox("Checkbox 5", cbg, false);
cb6 = new Checkbox("Checkbox 6", cbg, false);
How to Use the Choices
Choice class provides a menu-like list of choices, accessed by the distinctive
button. User presses the button to bring up the "menu", and later chooses one of
the items from the menu list. Another name for this UI element is the "pop-up list".
Other ways of providing the multiple alternatives are checkboxes, lists, and menus.
Below is an applet code which has a Choice and Label. When the user chooses item from
the Choice list, the Label changes to reflect an item chosen
This code creates the Choice and handles the events from it. Note:
that the second parameter to action() method is a string from the selected item.
//...Where instance variables are defined:
Choice choice; //pop-up list of choices
//...Where initialization occurs:
choice = new Choice();
choice.addItem("ichi");
choice.addItem("ni");
choice.addItem("san");
choice.addItem("shi");
label = new Label();
setLabelText(choice.getSelectedIndex(), choice.getSelectedItem());
. . .
public boolean action(Event e, Object arg)
{
if (e.target instanceof Choice)
{
setLabelText(choice.getSelectedIndex(), (String)arg);
return true;
}
return false;
}
}
How to Use the Dialogs
The thing that distinguishes dialogs from regular windows (that are implemented
with Frame objects) is that the dialog is dependent on some other window (i'e Frame).
When this other window is destroyed, and so are its dependent dialogs. When that other
window is been iconified, its dependent dialogs will disappear from the screen. When
the window is been deiconified, its dependent dialogs return to the screen. The
AWT automatically provides this behavior to us.
Since no API currently do exists to let the applets find the window they are running in,
applets generally cannot use dialogs. The exception is the applets that bring up their
own windows can have the dialogs dependent on those windows. For this reason, the
following applet consists of the button that brings up window which brings up a dialog.
Here is the code for the window which the applet brings up. This code can be run
as an standalone application or, with the help of AppletButton class, as an applet
Here is the code that deals with the Dialog object:
//[HOW DO I MAKE THIS GET THE FOCUS?]
class SimpleDialog extends Dialog
{
private TextField field;
private DialogWindow parent;
private Button setButton;
The Frame class provides the windows for applets and applications. Every application
needs atleast one Frame. If an application has the window that should be dependent on
another window -- disappearing when other window is iconified, for example -- then
you should use the Dialog instead of Frame for the dependent window. (Unfortunately,
applets cannot use the dialogs currently well, so they need to use the frames.)
Below is a code for the menu demonstration uses to create the window
and handle the case where the user closes window.
public class MenuWindow extends Frame
{
private boolean inAnApplet = true;
private TextArea output;
public MenuWindow()
{
//This constructor implicitly calls the Frame no-argument
//constructor and then adds components to the window.
}
public boolean handleEvent(Event event)
{
if (event.id == Event.WINDOW_DESTROY)
{
if (inAnApplet)
{
dispose();
} else
{
System.exit(0);
}
}
return super.handleEvent(event);
}
. . .
public static void main(String args[])
{
MenuWindow window = new MenuWindow();
window.inAnApplet = false;
Label class provides an easy way for putting uneditable, unselectable text into the
program's GUI. The labels are aligned to the left of their drawing area, by default.
we can specify that they be centered or right-aligned by specifying the Label.CENTER or
by Label.RIGHT either to Label constructor or to setAlignment() method. As
with every Component, you can also do specify the font and color of the Label.
Given below are the applets that use labels. The first applet (LabelDemo) simply creates
three labels with a default (left) alignment, puts them in the GridLayout, and then
displays them. Here is the code for LabelDemo.
import java.awt.*;
import java.applet.Applet;
public class LabelDemo extends Applet
{
public void init()
{
Label l1 = new Label();
l1.setText("Label 1");
Label l2 = new Label("Label 2");
Label l3 = new Label("Label 3");
//Add Components to the Applet.
setLayout(new GridLayout(0, 1));
add(l1);
add(l2);
add(l3);
validate();
}
}
The second applet (LabelAlignDemo) does same, except that it make use of all three
possible alignments. Since the applet is wider than necessary to display the text,
and because the GridLayout uses all the available space, Labels have the wider display
area than they need. This results in the visible difference in a horizontal position of
the three differently aligned labels.
import java.awt.*;
import java.applet.Applet;
public class LabelAlignDemo extends Applet
{
public void init()
{
Label l1 = new Label();
l1.setText("Left");
Label l2 = new Label("Center");
l2.setAlignment(Label.CENTER);
Label l3 = new Label("Right", Label.RIGHT);
//Add Components to the Applet.
setLayout(new GridLayout(0, 1));
add(l1);
add(l2);
add(l3);
validate();
}
}
Below is a code that LabelAlignDemo uses to create the labels and set their alignment.
For the purpose of teaching, this applet uses all the three Label constructors.
Label l1 = new Label();
l1.setText("Left");
Label l2 = new Label("Center");
l2.setAlignment(Label.CENTER);
Label l3 = new Label("Right", Label.RIGHT);
How to Use the Lists
List class provides the scrollable area containing the selectable text items
(one for each line). Lists can allow either a multiple selections or only one selection
at a time. Other components that allows the users to choose from the multiple selections
are checkboxes (checkbox groups particularly), choices, and menus.
Below is code for an applet that shows two lists. The first list
(which lists out the Spanish numbers) allows multiple selections.
The second list (which lists the Italian numbers) allows a maximum
of one selection.
Below is a code which creates each list and handles events on the list.
Note : the e.arg data for action events is the name of an acted-on
item (similar to argument for action events on other components such as buttons and
the menus). However, e.arg data for other list events is a number of acted-on
item.
//where instance variables are declared:
TextArea output;
List spanish, italian;
//where initialization occurs:
//Build first list, which allows multiple selections.
spanish = new List(4, true); //prefer 4 items visible
spanish.addItem("uno");
spanish.addItem("dos");
spanish.addItem("tres");
spanish.addItem("cuatro");
spanish.addItem("cinco");
spanish.addItem("seis");
spanish.addItem("siete");
//Build second list, which allows one selection at a time.
italian = new List(); //Defaults to none visible, only one selectable
italian.addItem("uno");
italian.addItem("due");
italian.addItem("tre");
italian.addItem("quattro");
italian.addItem("cinque");
italian.addItem("sei");
italian.addItem("sette");
. . .
public boolean handleEvent(Event e)
{
if (e.target instanceof List)
{
List list = (List)(e.target);
String language = (list == spanish) ?
"Spanish" : "Italian";
switch (e.id)
{
case Event.ACTION_EVENT:
String string = (String)e.arg;
output.appendText("Action event occurred on \""
+ string + "\" in "
+ language + ".\n");
break;
case Event.LIST_SELECT:
int sIndex = ((Integer)e.arg).intValue();
output.appendText("Select event occurred on item #"
+ sIndex + " (\""
+ list.getItem(sIndex) + "\") in "
+ language + ".\n");
break;
case Event.LIST_DESELECT:
int dIndex = ((Integer)e.arg).intValue();
output.appendText("Deselect event occurred on item #"
+ dIndex + " (\""
+ list.getItem(dIndex) + "\") in "
+ language + ".\n");
}
}
return super.handleEvent(e);
}
How to Use the Menus
The applet given above shows many of the menu features we are likely to use. The window
it brings up has menu bar which contains four menus. Each menu contains one or more
than one items. Menu 1 is a tear-off menu; by clicking a dashed line
[implementation-specific?], we create a new window which contains same menu items as
the Menu 1. Menu 2's only item has a checkbox. Menu 3 contains the separator between
its second and the third items. Menu 4 is a window's help menu, which (depending on
a platform) generally means that it is set off to the right. When we click on any menu
items, the window displays the string indicating which item has been clicked and what
menu it is in.
Here is the code for the window which the above applet brings up. This code can run
as an standalone application or, with the help of an AppletButton class, as an applet.
Here is the code that deals with menus:
//Build the menu bar.
mb = new MenuBar();
setMenuBar(mb);
//Build first menu in the menu bar.
m1 = new Menu("Menu 1", true);
mb.add(m1);
mi1_1 = new MenuItem("Menu Item 1_1");
m1.add(mi1_1);
mi1_2 = new MenuItem("Menu Item 1_2");
m1.add(mi1_2);
//Build help menu. Note that order in which it's added doesn't matter.
m4 = new Menu("Menu 4");
mb.add(m4); //Just setting the help menu doesn't work; must add it.
mb.setHelpMenu(m4);
mi4_1 = new MenuItem("Menu Item 4_1");
m4.add(mi4_1);
mi4_2 = new MenuItem("Menu Item 4_2");
m4.add(mi4_2);
//Build second menu in the menu bar.
m2 = new Menu("Menu 2");
mb.add(m2);
mi2_1 = new CheckboxMenuItem("Menu Item 2_1");
m2.add(mi2_1);
//Build third menu in the menu bar.
m3 = new Menu("Menu 3");
mb.add(m3);
mi3_1 = new MenuItem("Menu Item 3_1");
m3.add(mi3_1);
mi3_2 = new MenuItem("Menu Item 3_2");
m3.add(mi3_2);
m3.addSeparator();
mi3_3 = new MenuItem("Menu Item 3_3");
m3.add(mi3_3);
mi3_4 = new MenuItem("Menu Item 3_4");
mi3_4.disable();
m3.add(mi3_4);
}
public boolean action(Event event, Object arg)
{
String str = "Action detected";
if (event.target instanceof MenuItem)
{
MenuItem mi=(MenuItem)(event.target);
str += " on " + arg; v
if (mi instanceof CheckboxMenuItem)
{
str += " (state is "
+ ((CheckboxMenuItem)mi).getState()
+ ")";
}
MenuContainer parent = mi.getParent();
if (parent instanceof Menu)
{
str += " in " + ((Menu)parent).getLabel();
} else
{
str += " in a container that isn't a Menu";
}
}
str += ".\n";
//...Display string in the output area...
return false;
}
public boolean handleEvent(Event evt)
{
switch (evt.id)
{
case Event.SCROLL_LINE_UP:
case Event.SCROLL_LINE_DOWN:
case Event.SCROLL_PAGE_UP:
case Event.SCROLL_PAGE_DOWN:
case Event.SCROLL_ABSOLUTE:
if (evt.target == vert)
{
canvas.ty = ((Integer)evt.arg).intValue();
canvas.repaint();
}
if (evt.target == horz)
{
canvas.tx = ((Integer)evt.arg).intValue();
canvas.repaint();
}
}
return super.handleEvent(evt);
}
How to Use the TextAreas and TextFields
//Where instance variables are defined:
TextField textField;
TextArea textArea;
public void init()
{
textField = new TextField(20);
textArea = new TextArea(5, 20);
textArea.setEditable(false);
...//Add the two components to the panel.
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.ACTION_EVENT)
{
String text = textField.getText();
textArea.appendText(text + "\n");
textField.selectAll();
}
return super.handleEvent(evt);
}