Chapter 6

Simple Input and Output


CONTENTS

In the previous chapter, you learned how you can store various types of values in your Java programs. It may have occurred to you that it doesn't do much good to store data in a computer's memory if you have no way of actually seeing that data. Also, you need a way to request and receive data from users of your programs. Both of these tasks-displaying and retrieving data-are accomplished through simple input and output, or I/O (as it's commonly called). In this chapter, you'll learn how Java enables you to perform simple I/O in your applets.

Windows and Graphics

Because you'll be writing your applets for a graphical user interface (GUI) such as Windows, you can't use the same kinds of data input/output that you may have been accustomed to using under another operating system, such as MS-DOS. This is because, under a system such as Windows, everything that appears on the screen is graphical (unlike MS-DOS, which displays plain old text).

Still, displaying graphical text doesn't require a whole lot of work, as long as you're not concerned with things like fonts and the size of the text string you want to display. You have to remember, though, that almost all graphical text is proportional, meaning that each letter in a line of graphical text takes up a different amount of space. Under an operating system like MS-DOS, most text output uses non-proportional characters. The difference is illustrated in Figure 6.1.

Figure 6.1 : In a proportional font, each character takes up only as much space as it needs.

Look at the letter "I" in the proportional font. You can see that it takes up much less space than other letters in the word. On the other hand, the letter "I" in the non-proportional font, as well as the hyphen, takes up exactly the same amount of space as every other letter.

The point is that, because of the different fonts that are used to print text in a graphical user interface, you can't assume much about the size of the text that'll be used. There are ways to figure out the actual size of a text string, but you don't have to be concerned with these details for now. Just be aware that text output in your applets is going to be graphical.

Displaying Text in an Applet

The easiest thing to display is a line of text. But because the text output will be graphical, you need to use one of Java's graphical-text functions. The most commonly used is drawString(), which is part of the Graphics class contained in the awt package. Listing 6.1 shows a simple applet that uses this method to display a single line of text. Figure 6.1 shows what the applet looks like when viewed with the Appletviewer application. Finally, Listing 6.2 is an HTML document that tests the Applet1 applet.

NOTE
A package is nothing more than a collection of related classes. The awt (abstract windows toolkit) package contains all the classes that handle graphical windows. You'll learn a lot more about classes, packages, and the awt later in this book.


Listing 6.1  Applet1.java: An Applet That Displays a Single Line of Text.

import java.awt.*;

import java.applet.*;



public class Applet1 extends Applet

{

    public void paint(Graphics g)

    {

        g.drawString("Hello from Java!", 60, 75);

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet1 class from Java's Applet class.
Override the Applet class's paint() method.
Draw a text string on the applet's surface.
Figure 6.2 : When you run the Applet1 applet, you'll see a single line of text in the applet's display.


Listing 6.2  APPLET1.htmL: An HTML Document for Testing Applet1.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="Applet1.class"

    width=200

    height=150

    name="Applet1">

</applet>


Example: Creating and Running Applet1

In the next section, you'll see exactly how the Applet1 applet works. But before you get too much farther, you need to know how to create and run the many applets that you'll find in this book. All the applets that follow use the same sort of procedure. This procedure involves creating the applet's source code, compiling the code, and then writing the HTML document that demonstrates the applet. Follow the steps below to get the Applet1 applet up on your screen.

  1. Create a folder called CLASSES on the root directory of your hard drive.
  2. Type Listing 6.1 and save it in the CLASSES folder as an ASCII file. Name the file Applet1.java. (Use uppercase and lowercase letters exactly as shown for the program's file name.) Note that you can also copy the listing from this book's CD-ROM, if you don't want to type it.
  3. Start an MS-DOS session by selecting Start/Programs/MS-DOS Prompt. If the MS-DOS screen takes over the entire screen, press Alt+Enter to display the MS-DOS session in a window.
  4. If you haven't added the JAVA\BIN path to your AUTOEXEC.BAT file, type PATH=JAVA\BIN at the MS-DOS prompt. This ensures that the system will be able to find Java's executables.
  5. Type cd c:\classes to move to your CLASSES folder.
  6. Type javac Applet1.java to compile the Applet1 applet. You should receive no error messages, as shown in Figure 6.3. If you do receive error messages, carefully check your typing of Listing 6.1. Also, make sure you typed the command line javac Applet1.java properly. When the compiler finishes, you'll have the file Applet1.class in your CLASSES directory. This is the applet's byte-code file.
    Figure 6.3 : The Applet1.class file must compile with no errors.

  7. Type Listing 6.2 and save it as an ASCII file to your CLASSES folder. Name the file APPLET1.htmL. (This time, the case of the letters doesn't matter.)
  8. At the MS-DOS prompt, type appletviewer applet1.html (case doesn't matter). When you do, Appletviewer will load and display the applet.

NOTE
Java insists that the name of a Java source-code file is the same name as the class contained in the file. If you try to use different names, even if the difference is only the case of a letter or two, the Java compiler will complain and refuse to compile the program.

How Applet1 Works

By now, you have the source code for Applet1 properly typed and compiled. You've even run the applet using Appletviewer. You know that the call to the drawString() method prints a string as graphical text in the applet's display area. But what are the values between drawString()'s parentheses? And how does the program know when to execute the call to drawString()?

First, look at the paint() method. Java calls paint() whenever the applet's display area (or canvas, as it's often called) needs to be redrawn. The paint() method always gets called when the applet first appears on the screen, which is exactly what's happening in Applet1. You run the applet, Java calls paint() when the applet appears, and paint() calls drawString(), which displays the text string "Hello from Java."

NOTE
The Java compiler is case-sensitive, meaning that it can differentiate between upper- and lowercase letters. For this reason, you have to be extra careful to type method names properly. For example, if you type Paint() instead of paint(), Java will not recognize the method and will not call it when the applet needs to be redrawn.

What's that "g" followed by a period in front of the call to drawString()? Remember that I said drawString() is a method of the Graphics class. If you look at the first line of the paint() method, you'll see Graphics g in the parentheses. This means that Java is sending an object of the Graphics class to the paint() method and that object is called g. Whenever you need to call an object's method, you must preface the method's name with the object's name followed by a period. So, the line


g.drawString("Hello from Java!", 60, 75);

tells Java to call the g object's drawString() method. The values in the parentheses are called arguments, which are values that you need to send to the method. The arguments in the above call to drawString() tell Java to draw the text "Hello from Java!" at column 60 and row 75 of the display area. (The position is measured in pixels, not characters. A pixel is the smallest dot that can be displayed on the screen.) To display the text at a different location, just change the second and third arguments. For example, Figure 6.4 shows the text positioned at 25,25.

Figure 6.4 : Here, Applet1 displays the text at position 25,25.

Getting Input from the User

Again, because you are now programming in a graphical environment, getting input from the user isn't as easy as just calling an input command. You must first create an area of the screen in which the user can type and edit his response to your request. There are several ways to do this, but one of the easiest is to add a control of the TextField class in your applet. A TextField control is much like the edit boxes you see when using Windows. You might, for example, see a number of edit controls in a dialog box. Listing 4.3 shows how to include a TextField control in your applet. Figure 6.5 shows the Applet2 applet in action.

Figure 6.5 : The Applet2 applet displays an area in which you can type.


Listing 6.3  Applet2.java: Getting Input from the User.

import java.awt.*;

import java.applet.*;



public class Applet2 extends Applet

{

    TextField textField;



    public void init()

    {

        textField = new TextField(20);

        add(textField);

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet2 class from Java's Applet class.
Declare textField as an object of the TextField class.
Override the Applet class's init() method.
Create the new TextField object.
Add the TextField object to the applet's display.

To run the Applet2 applet yourself, you'll need to type and save the source code, naming it Applet2.java. (You can copy the source code from the CD-ROM, if you like, and thus save on typing. Of course, you won't learn as much that way.) Then compile the source code (type javac Applet2.java at the MS-DOS prompt), which gives you the Applet2.class file. Next, create a new HTML document from the one shown in Listing 6.2, changing all instances of Applet1 to Applet2. You can then run Applet2 by typing appletviewer applet2.html at the DOS prompt.

How Applet2 Works

Applet2 looks quite a bit different from Applet1. First, it declares a data field named textField as an object of the TextField class, which represents a control very much like a standard Windows edit box. The program declares the control like this:


TextField textField;

Notice that the textField object is declared just as you would declare any other kind of data object such as an integer or a floating-point value. Next, notice that, although the name of the class and the name of the object are spelled identically, the object's name starts with a lowercase letter. This makes all the difference in the world to Java, which is a case-sensitive language.

Another difference between Applet1 and Applet2 is that Applet2 has an init() method instead of paint(). The Init() method is another of those methods that Java calls automatically-in this case, as soon as you run the Applet2 applet. Because Java calls init() almost immediately, it's a great place to initialize the applet. (Guess that's why they called it init(), huh?)

In Applet2, when init() gets called, textField has already been declared as an object of the TextField class, but textField hasn't yet been assigned a value. The first line of code in init() creates the TextField object and assigns it to textField, like this:


textField = new TextField(20);

After Java executes this line, textField refers to an actual TextField object. The value in the parentheses is the width of the TextField control; the larger this number, the wider the control. Keep in mind that a textField control can hold more text than its width allows. If you type past the end of the control's text box, the text scrolls horizontally.

The next step is to add the object to the applet's display area, like this:


add(textField);

The add() method's single argument is the control you want to add to the applet.

After creating the control and adding it to the applet, the control will automatically appear when Java draws the applet. You don't need a paint() method to draw a control, because the control can take care of itself.

Once the TextField control is on the screen, you can type in it. First, click the control to give it the focus, then type and edit to your heart's content.

Example: Retrieving text from a TextField control

In the Applet2 applet, you can type all you like in the TextField control, but how do you get the text out of the control and actually do something with it? Follow the steps below to create Applet3, a new version of Applet2 that can retrieve and display any text entered into the TextField control.

  1. Type Listing 6.4 and save it in the CLASSES folder as an ASCII file. Name the file Applet3.java. Note that you can copy the listing from this book's CD-ROM if you don't want to type it.

Listing 6.4  Applet3.java: Source Code for the Applet3 Applet.

import java.awt.*;

import java.applet.*;



public class Applet3 extends Applet

{

    TextField textField;



    public void init()

    {

        textField = new TextField(20);

        add(textField);

    }



    public void paint(Graphics g)

    {

        String s = textField.getText();

        g.drawString(s, 40, 50);

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet3 class from Java's Applet class.
Declare textField as an object of the TextField class.
Override the Applet class's init() method.
Create the new TextField object.
Add the TextField object to the applet's display.
Override the Applet class's paint() method.
Get the text string from the TextField control.
Display the text in the applet's display area.
Override the Applet class's action() method.
Force the applet to redraw its display area.
Tell Java that the action() method finished successfully.
  1. Start an MS-DOS session by selecting Start/Programs/MS-DOS Prompt. If the MS-DOS screen takes over the entire screen, press Alt+Enter to display the MS-DOS session in a window.
  2. Type cd c:\classes to move to your CLASSES folder.
  3. Type javac Applet3.java to compile the Applet3 applet. You should receive no error messages. If you do receive error messages, carefully check your typing of Listing 6.4. Also, make sure you typed the command line javac Applet3.java properly.
  4. Modify Listing 6.2 by replacing all occurrences of Applet1 with Applet3 and save it as an ASCII file to your CLASSES folder. Name the file APPLET3.htmL.
  5. At the MS-DOS prompt, type appletviewer applet3.html. When you do, Appletviewer will load and display the applet.

When you run Applet3, go ahead and type some text into the TextField control. When you press Enter, the text appears in the applet's display area, right below the control (Figure 6.6).

Figure 6.6 : Applet3 can display the text you type into the TextField control.

How Applet3 Works

If you look at the Applet3 program code, you can see that you've added a paint() method. This is where the text that the user types into the TextField control gets displayed. First, paint() extracts the text from the control, like this:


String s = textField.getText();

This line declares a variable called s to be an object of the String class, and then it sets s equal to the text string in the control. (The String class is another of Java's built-in classes that you'll learn more about later. For now, just know that this class represents text strings.) You can see in this line that you're calling the textField object's getText() method, because of the object and method name separated by the dot. The getText() method simply returns the text string that's stored in the textField control.

Displaying the string is as easy as calling on your old friend drawString(), as follows:


g.drawString(s, 40, 50);

One big difference between Applet2 and Applet3 is the action() method. Java calls this method whenever the user performs some action with controls in the applet. In this case, the action that action() responds to is the user's pressing Enter after typing text. In Applet3, the action() method does nothing more than call the applet's repaint() method, which tells Java that you want to redraw the applet's display area. (You'll learn more about using the action() method later in the book.) This causes Java to call the paint() method, which very neatly displays the control's string.

Displaying Numerical Values

In the previous chapter, you learned to declare and define a number of different variable types, including int, byte, short, float, and other numerical values. The problem with numerical values in a computer is that you can't display them without first converting them to text strings. Luckily, this task is pretty easy to perform. You need only call the String class's valueOf() method, as shown in Listing 6.5. Figure 6.7 shows Appletviewer running Applet4.

Figure 6.7 : The Applet4 applet converts and displays an integer value.


Listing 6.5  Applet4.java: The Source Code for Applet4.

import java.awt.*;

import java.applet.*;



public class Applet4 extends Applet

{

    public void paint(Graphics g)

    {

        int x = 10;

        String s = String.valueOf(x);

        g.drawString(s, 40, 50);

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet4 class from Java's Applet class.
Override the Applet class's paint() method.
Declare the integer x and set its value to 10.
Convert x to a string.
Display the string that represents x's value.

As you can see in Listing 6.5, the String class has a method called valueOf() that can convert numerical values to strings. The method's single argument is the value you want to convert, which can be any of Java's numerical data types.

Summary

All computer programs must deal with some form of I/O. At the very least, a program must be able to display information to the user, as well as retrieve data from the user. Java has several ways to handle this basic form of I/O, a couple of which you learned in this chapter. As you dig deeper into the art of writing Java applets, you'll see other ways to perform I/O.

Review Questions

  1. What is graphical text?
  2. What's the difference between proportional and non-proportional fonts?
  3. What are arguments?
  4. Describe the three arguments used with the drawString() method.
  5. What does the paint() method do?
  6. Describe one way to get user input in your applets.
  7. Describe how the init() method works.
  8. Describe how the action() method works.
  9. How can you convert a numerical value to a text string?

Review Exercises

  1. Modify Applet1 so that it displays the text string "Out to lunch!" at position 30, 50 in the applet's display area.
  2. Modify Applet2 so that it displays a TextField control half as wide as the one displayed in the original program.
  3. Write an applet that displays the days of the week in a column down the center of the applet's display area.
  4. Using Applet3 as a model, write a new applet called NameApplet that asks the user for her name and age and then prints the answers in the applet's display area. The finished applet should look like Figure 6.8. (This one's tough, so, if you get stumped, check out the file NameApplet.java in the CHAP06 folder of this book's CD-ROM. First try to solve the problem yourself, though.)
    Figure 6.8 : This is what the NameApplet applet should look like when it is run with Appletviewer.