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.
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
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.
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>
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.
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. |
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.
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.
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.
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.
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.
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.
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.
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.
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.