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

PhoneTextField Help

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

Task 1

Create an Applet to hold one instance of PhoneTextField so that you can test your component.

You need to create a class separate from your LabeledTextField class. You can call it LabeledTextFieldTest. In this class, create an instance of LabeledTextField and add it to the container. Here, as you did with LabeledTextField, use a GridLayout to manage the container so that the PhoneTextField will be scaled to fit the window rather than appearing at its preferredSize.

import java.awt.*;

public class PhoneTextFieldTest extends java.applet.Applet {

    public void init() {
        setLayout(new GridLayout(1,1));
        PhoneTextField test = new PhoneTextField();
        add(test);
    }
}

Task 2

Create the class PhoneTextField as a subclass of LabeledTextField. Make the constructor set the label to "Phone Number".

class PhoneTextField extends LabeledTextField {

    public PhoneTextField() {
        super("Phone Number");
    }
    ...
}

Task 3

Override the method verify of FormElement so an error is printed if the text contains any nondigits, or does not have the right number of digits (either 7 or 10). Set the text to "" upon error.

public void verify() {
    StringBuffer    buffer = new StringBuffer();
    StringTokenizer st     = new StringTokenizer(text.getText(), "()- ");
    // remove parentheses, spaces and dashes
    while (st.hasMoreTokens()) {
        buffer.append(st.nextToken());
    }
    // make sure there are numbers
    try { Integer.parseInt(buffer.toString()); }
    catch (NumberFormatException e) {
        System.err.println("Only digits are allowed:  " +
                            "Please enter again.");
        text.setText("");
    }
    // right length?
    if (buffer.length() != 7 && buffer.length() != 10) {
        System.err.println("Not the right number of digits:  " +
                           "Please enter again.");
        text.setText("");
    }
}