Technical Support
Discussion Forum
Online Training
Read About Java
Java In-Depth
Product Discounts
Membership Information

Java Cup Logo

JDC Home Page


Working Applet
Help and Hints
Source Code
Table of Contents
Online Training
shadowSearchFAQFeedback

Choice Help

Help is available for each task, or you can go straight to the Choice source code to see a solution.

Task 1

Create an applet called ChoiceTest. In the init method, create and add an object called MyChoice that you will create later.

import java.awt.*;
public class ChoiceTest extends java.applet.Applet {
    public void init() {
        MyChoice flavors = new MyChoice();
        add(flavors);
    }
}

Task 2

Create a class called MyChoice that extends Choice. In its constructor, add three items: "Chocolate", "Vanilla", and "Strawberry".

Items are added to a Choice via the addItem method:

class MyChoice extends Choice {
    public MyChoice() {
        addItem("Chocolate");
        addItem("Vanilla");
        addItem("Strawberry");
    }
}

Task 3

Define the method action in MyChoice so that when the user selects an item, it is printed to System.out.

The action method will be called whenever a user selects an item from the Choice. The argument is the String item that was selected and you can simply print it to System.out.

class MyChoice extends Choice {
    ...
    public boolean action(Event e, Object color) {
        System.out.println("selected " + color);
        return true;
    }
}