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

CommentBox Help

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

Task 1

Create an Applet to hold one instance of CommentBox so that you can test the component.

You need to create a class separate from your CommentBox class. You can call it CommentBoxTest. In this class, create an instance of CommentBox and add it to the container.

import java.awt.*;

public class CommentBoxTest extends java.applet.Applet {
    public void init() {
        CommentBox test = new CommentBox();
        add(test);
    }
}

Task 2

Create a class called CommentBox as a subclass of FormElement.

public class CommentBox extends FormElement {
    ...
}

Task 3

In the class CommentBox, create a centered Label and a TextArea below it. Make the TextArea display three lines of 55 characters.

You have to create a constructor to initialize the components needed by the compound component, and add them to the current Container. In this case, the Container is a Panel since FormElement subclasses Panel:

class CommentBox extends FormElement {
    protected TextArea text;
    protected String   label = "Comments";
    public CommentBox() {
        setLayout(new BorderLayout());
        text = new TextArea(3, 55);
        add("North",  new Label(label, Label.CENTER));
        add("Center", text);
    }
    ...
}

text and label are instance variables so that other methods in this class will have access to them.

Task 4

Implement the method isEmpty of FormElement to return true if the TextArea is empty.

public boolean isEmpty() {
    return text.getText().equals("");
}

Task 5

Implement the method getContents of FormElement. It should return the Label and the contents of the CommentBox.

public String getContents() {
    return label + "    " + text.getText();
}