Chapter 18

Label and Button Controls


CONTENTS

Many computer applications require that the user enter information that the program needs to perform its tasks. In a windowed, graphical environment, getting information from the user presents a challenge. This is because the currently executing application doesn't control the entire screen and so can't just take control of the keyboard or other input device in order to obtain information from the user. That's why the developers of graphical user interfaces created the various controls-such as text boxes, buttons, and menus-that enable applications to interact with the user without bringing the rest of the system to a halt.

Because Java applets must run under many different windowed operating systems, the Java Developer's Kit provides classes for creating the basic controls needed by most graphical user interfaces. These controls include labels, text fields, buttons, radio buttons, check boxes, and choice menus. In this chapter, you learn to program and manage the label and button controls. Other controls are covered in succeeding chapters.

Labels

Labels are the simplest of Java's controls, being little more than text strings you can place anywhere on your applet's display area. You create a label by calling the Label class's constructor, like this:


Label label = new Label(str, align);

The Label class's constructor takes two arguments, which are the text to display and an alignment value. The alignment value can be Label.LEFT, Label.CENTER, or Label.RIGHT. After creating the label, you add it to the applet by using the add() method, like this:


add(label);

Example: Creating a Label

Suppose that you want a centered label that displays the text Java does labels! To do this, you use a line of Java code something like this:


Label label = new Label("Java does labels!", Label.CENTER);

Of course, you can also store the text to display in a String object, like this:


String str = "Java does Labels!";

Label label = new Label(str, Label.CENTER);

One cool thing about labels is that they automatically retain their alignment when the size of an applet's display area changes. For example, Figure 18.1 shows an applet displaying the centered label created in the previous example. In Figure 18.2, the user has increased the size of the Appletviewer window. The label adjusts to the new space, automatically staying centered.

Figure 18.1 : Labels are great for creating text strings that align automatically.

Figure 18.2 : Here, the label has repositioned itself so that, in spite of the enlarged window, the label stays centered.

Methods of the Label Class

After you create a Label object, you can use the class's methods to manipulate the label. Specifically, you can get or set the label's text and alignment, as shown by the methods listed in Table 18.1.

Table 18.1  Methods of the Label class.

MethodDescription
int getAlignment()Retrieves a label's alignment setting.
String getText()Retrieves a label's test string.
setAlignment(int align)Sets a label's alignment.
void setText(String label)Sets a label's text string.

The getAlignment() and getText() methods have no arguments. The argument for the setAlignment() is the alignment value (Label.LEFT, Label.CENTER, or Label.RIGHT), and the argument for setText() is the new text for the label.

NOTE
A label's text is displayed using the currently set font. You can create labels that use different fonts by creating and setting the font before creating the label.

Buttons

In a few previous applets, you used buttons to enable the user to manipulate some feature of the applet. Buttons are a great way to trigger events in your applet because they're easy to create and manage, and, most importantly, they're easy for the user to use. To create a button, you first call the Button class's constructor, like this:


Button button = new Button(str);

Here, str is the text string that you want to appear on the button.

Like other Java classes, Button features methods you can use to manipulate a button object. You use these methods to retrieve or set the button's text, like this:


String button.getLabel();

button.setLabel(str);

Example: Adding a Button to an Applet

Adding buttons to your applets is painfully easy. Just create the button, and then call the add() method to add the button to the applet. When the applet runs, the user will be able to interact with the button, generating events that the applet can respond to as appropriate. For example, suppose that you want to add a button for setting a font. First, you create a button with an appropriate label, like this:


Button button = new Button("TimesRoman");

Then, you call the add() method to add the button object to the applet, like this:


add(button);

Now, when the applet appears in your Web page, the user can click the button to trigger an event that tells your applet which font to display.

Handling Multiple-Button Events

In previous applets that contained buttons, you responded to the button in the applet's action() method. When the user clicked the button, Java called action(), and you did whatever you needed to do in that method. However, what if you have more than one button? Then, you need some way to figure out which button was clicked so the applet can respond properly.

As it turns out, the action() method delivers two parameters to your program when it's called, as you can see by examining the function's signature:


public boolean action(Event evt, Object arg)

The first parameter, evt, is an Event object, and arg, the second parameter, is, in the case of a button, the button's label. (The value type of the second parameter changes depending on the interface object.) The target field of an Event object indicates the type of object that generated the event. To determine the object, you use the instanceof keyword, like this:


if (evt.target instanceof Button)

If this if statement is true, it was a button object that generated the event. To determine exactly which button caused the event, you examine the arg parameter, like this:


if (arg == str)

In this line, str is the button's label. If the comparison is true, you know exactly which button was clicked.

Example: Handling Multiple Buttons in an Applet

To get a better understanding of how button events work, take a look at the applet shown in Listing 18.1. ButtonApplet displays three buttons in its display area, as shown in Figure 18.3. Whenever you click a button with a normal label, its label reverses itself, as shown in Figure 18.4. When you click a button with an already reversed label, all the labels return to their normal state.

Figure 18.3 : The ButtonApplet applet displays three buttons.

Figure 18.4 : When you click a button with a normal label, the label reverses itself.


Listing 18.1  ButtonApplet.java: An Applet with Multiple Buttons.

import java.awt.*;

import java.applet.*;



public class ButtonApplet extends Applet

{

    Button button1;

    Button button2;

    Button button3;



    public void init()

    {

        button1 = new Button("Button1");

        button2 = new Button("Button2");

        button3 = new Button("Button3");



        add(button1);

        add(button2);

        add(button3);

    }



    public boolean action(Event evt, Object arg)

    {

        if (evt.target instanceof Button)

            HandleButtons(arg);

        return true;

    }



    protected void HandleButtons(Object label)

    {

        if (label == "Button1")

            button1.setLabel("1nottuB");

        else if (label == "Button2")

            button2.setLabel("2nottuB");

        else if (label == "Button3")

            button3.setLabel("3nottuB");

        else

        {

            button1.setLabel("Button1");

            button2.setLabel("Button2");

            button3.setLabel("Button3");

        }

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ButtonApplet class from Java's Applet class.
Declare three button objects.
Override the init() method.
Create the three buttons.
Add the buttons to the applet's display.
Override the action() method.
If a button was pressed, call the HandleButtons() method.
Tell Java that the event was handled okay.
Define the HandleButtons() method.
Convert the size to a string.
if the button's label is normal, reverse it.
Else set all the button's labels back to normal.

Summary

Because a program running in a windowed environment cannot take exclusive control of a computer's resources, applets require special controls to send and retrieve information to and from the user. Two such controls are labels, which enable you to display short text strings, and buttons, which enable the user to select commands with a single mouse click. When clicked, a button object triggers an event that you can capture and respond to in the applet's action() method. By writing Java source code to handle the button click, you can implement many types of button-controlled commands in your applets. In following chapters, you'll learn about other Java controls, including checkboxes, choice menus, and scroll bars.

Review Questions

  1. What are the two arguments required by the Label class's constructor?
  2. What happens to a label's alignment when the size of an applet changes?
  3. How do you add controls to an applet?
  4. What is the single argument needed by the Button class's constructor?
  5. What are the values you can use to set a label's alignment?
  6. What two attributes of a label object can be set using the class's methods?
  7. How can you change the label displayed in a button control?
  8. When a user clicks a button control, what arguments are received by the action() method?
  9. In an applet with several button controls, how can you determine which button was clicked?
  10. What happens when the user clicks a label?

Review Exercises

  1. Write an applet that displays the label Java rules!
  2. Write an applet that creates a button control with the label Command.
  3. Write an applet that contains three button controls. When the user clicks a button, display the button's label in the area below the buttons.
  4. Write an applet that contains two labels and two buttons organized into two rows. Each row should start with a label followed by a button. (Hint: The size of the applet given in its HTML document will determine how the controls are organized.)
  5. Write an applet called LabelButtonApplet that contains three buttons and three labels. When the user clicks a button, the associated label should reverse its text. Clicking on a button that's associated with a changed label should reverse the text again, back to its original form. The final applet should look like Figure 18.5. Figure 18.6 shows the applet with two labels changed. (You can find the solution to this problem in the CHAP18 folder of this book's CD-ROM.)

Figure 18.5 : This is the ButtonLabelApplet applet at startup.

Figure 18.6 : Here's ButtonLabelApplet after two labels have been reversed.