Copyright (c) 1999 by Charlie Calvert
This chapter is designed to show how to query the user for input, how to run simple calculations on that input, and how to display the results of your calculations. Here is a more detailed look at the subjects included in this chapter:
The structure of the chapter is simple. First, I'm going to show you how to build a new Applet called Adder that can accept input from the user. The user will be able to enter two integer values. The program will then add these numbers together, and show the result to the user. For instance the user might enter the numbers 3 and 4, the program would add them together to make 7, then display the result to the user.
After you have created the program, I'm going to show you three ways to deploy it on the web:
The adder program allows the user to enter two numbers. It adds the numbers and shows the result to the user. The main benefit of the program is that it shows you how to get input from the user.
Open up JBuilder and use the File menu to close any projects that currently happen to be open. Choose File | New to create a new applet. Call your project Adder.jpr, and put it in a directory called Adder:
/home/ccalvert/jproject/Adder/Adder.jpr
In the second page of the Wizard, set your title to Adder. In the third page, make sure you inherit from java.awt.Applet, and not from java.swing.JApplet. You should also choose to Generate Header Comments and Generate Standard Methods. There are no specific benefits for our program from choosing these last two options. As a result, you can select them or not depending on your preferences. However, it is easier to delete these comments and methods if you don't want them, than to try to think up the proper declaration for them.
Choose the Next button to keep moving through the wizard. You will not need to pass any parameters into this program, so you can leave the parameters page alone. Once again press the Next button. There is also no need to make any changes to the final page of the wizard.
NOTE: Again, there are no real benefits derived from stepping through the last two pages. As a result, you can press the Finish button before you reach them. However, I suggest you step through the pages just so you can get used to looking at them, and hopefully gain some sense of what they can do for you. Get the sense that you are the master of your programming environment. Do whatever is necessary to feel as comfortable as possible. Sometimes the simple act of exploring the environment, seeing what each of the options can do, can help you start to feel at home.
At this stage, you have a created your basic applet upon which you can build your program. If you had any trouble filling out any of these steps, then go back to the Chapter 2, "Creating a Simple Applet," to read a more detailed analysis of how to go through the basic steps outline in this section of the chapter.
The next step is to create the interface for the Adder program. Take a look at Figure 1 to get a sense of what it is you are trying to create. The interface is fairly simple, but there are a few tricks you need to master before you will feel at home creating programs like this. Once the interface is in place, then we can write the logic that makes the program do something useful.

Figure 1: The Adder program lets the user enter two integers and then press a button to add the numbers together and show the result.
The key thing to remember is not to drop just any old control you find on the component palette onto surface of your applet. Instead you must first turn to the AWT page. If you don't use controls from the AWT page, then your applet won't conform to the standards supported by most browsers.
Don't forget that you won't see the component palette unless you first click on Applet1.java in the navigator pane, and then click on the Design button near the bottom of the IDE. After you do this, you should be able bring up the AWT page, as shown in Figure 2. If you don't see the AWT page on the component palette, then push the little buttons on the right of the palette to scroll any hidden pages into view.
Figure
2: The AWT page of the component palette has java.awt.Button controls
on its far left, and java.awt.TextField controls on its far right.
Drop down three of the TextField controls and one of the Button controls.
By default, the controls you dropped on the applet will line up along the top of the form. In this particular case, we don't want the controls to line up that way. In fact, we don't want the controls to follow any of the normal patterns for laying out controls in Java. Instead, we want to lay controls out in our own way, as shown in Figure 1.
One simple way to get control over the layout of controls is to pick the null layout. Layouts are schemes designed to help you align your controls on a form. There are several different layout schemes available in JBuilder. Most of them will cause the components on your form to automatically align themselves according to some predefined scheme. For instance, some layouts will cause the controls to cling to the edges of the applet panel, and others will cause them to arrange themselves in a grid like pattern. An exploration of these various layouts will occur in another chapter.
In our case, we want to pick the null layout. This is not at all the best layout, but it is the easist one for beginners to use. To select this layout, first put the focus on the applet panel itself. You can do this either by clicking on the panel, or by clicking on the word "this" in the structure pane. Now look over at the inspector. Here you will see several properties of the panel, called name, background, componentOrientation, cursor, dropTarget, enabled, font, foreground, layout and visible. These properties are shown in Figure 3, and many of them will be discussed in various other portions of this text.

Figure 3: Viewing the inspector for the applet's panel.
The property we are interested in is called layout. To use the property, click the area on the right handside of the inspector, the portion that contains the word "null" in Figure 3. When you click in this area, you will find that there is a combobox you can drop down. Drop down the list and select the item from it that reads "null." Picking the null layout will give you complete control over the layout on your form.
NOTE: If you can't wait for me to explore the subject of layouts in more depth, or if you know where I'm headed and just want to get there as quickly as possible, then you can first lay things out using null, then switch to the GridBagLayout. Now right click on any one of the controls, and choose constraints. As you can see, the tools you need are all there. I will not, however, explore these tools until a later chapter. Furthermore, there is no need for you to understand this subject at this early stage. For now, you can just stick with the null layout unless you feel compelled to experiment or forge ahead on your own. (Not that there is anything wrong with forging ahead, mind you, but I have to impose some order on this text or it will be hard to read, and the chapters will be exceedingly long.)
After picking the null layout, you will be able to select each control and move it around on the form as you wish with the mouse. The first thing to do is arrange them as shown in Figure 2.
You might want help lining up the the controls. To elicit some aid, first click on one of the controls so that it is selected. Now hold down the control key and select each of the other TextField controls in turn by clicking on them once with the mouse. Use the same technique to select the button. Now right click on any one of the selected controls and select Align Left from the menu. Voila! All the controls line up automatically.
To deselect the controls, just click on any other control on the form that is not currently selected. For instance, you can click on the form itself.
NOTE: Lining up controls on a form is a simple process, but still things can go wrong. When you get started, make sure that the form itself is not selected. If you select the form, and several controls, and then choose align left, your results may not be what you expect. The problem is that the IDE is trying to line up all the selected controls along with the form itself. Sometimes that works out okay, and sometimes it doesn't.
Another easy error to make is to right click in the wrong place. If you have selected two or more controls, and want to align them, then you should right click on one of the selected controls to bring up the proper menu. If you right click on another part of the panel, then you won't see the proper menu.
The final member of my list of classic errors is to select all the controls on the form, and then the form itself. After taking those steps, its hard to find a way to deselect the controls. The problem is that all the controls on the form are selected, so you can't deselect through the standard method, which involves clicking on a non-selected control. One simple way out of this dilemma is to drop another control on the form. This will automatically deselect the other controls. Now you can delete the control you dropped on the form, and continue your work.
While I am on this subject, I'm going to mention one other trick that you should master. If you want to select three or four controls, you can left click the mouse, hold the button down, then drag a square over the controls you want to select. When you are done, all the controls you "netted" with the mouse will be selected.
When the user works with the program, he expects the controls to behave in a relatively sensible manner. One of the issues users tend to get fussy about is tab order. If the user is working inside the applet, and hits the tab button, they expect to focus to shift in a logical, predictable manner. If you are in the first TextField, and hit tab, do you move to the second TextField? Do you move to the Button? What is the tab order, and how is it controlled?
It turns out that the tab order is decided one way when you are using swing controls, and another way when you are using AWT controls. For now, we are using AWT controls, so we will focus on that technology. With AWT, the tab order is controled by the order in which controls are added to the form. The order in which tabs are added to a form is not necessarily the same order in which controls are created.
Turn to the source for Applet1.java, and find the section in the JBInit method that looks like this:
this.add(textField1, null);
this.add(textField2, null);
this.add(textField3, null);
this.add(addButton, null);
this.add(label1, null);
this.add(label2, null);The tab order is the same as the order in which these controls are added to the panel. In the code I show here, textField1 is first, and label2 is last. This means you can tab from textField1, to textField2, to textField3, and then to the addButton. Of course, label1 and label2 are not tab stops. That is, you can't focus these controls. This a peculiarity of label controls that makes sense if you think about it for a moment. A label control is meant to display text, and the user has no need to edit that text. As a result, label controls are inert. They can't get the focus, and thus they have no tab order.
Most of the time, it is simplest to change the tab order of controls by editing the source code, as I have shown here. However, it is also possible to change the order of the controls using the visual tools. Switch to design mode, right click on the control you want to change, and choose Move to First or Move to Last from the menu. If you do this, then switch back to the source, you will see that the code has been changed in the manner expected.
NOTE: The fact that Move to First or Move to Last changes the code in your program is actually very important. JBuilder has no black boxes. The visual tools might feel like a black box when you first look at them, but actually, they are just a visual way of changing the source in your program. Some tools have propriatary black boxes that conceal from you what is going on behind the scenes. With JBuilder, you can always see what is going on behind the scenes: just look at the source!
JBuilder tools are what are known as "two way tools." If you make changes using the visual tools, then the source is changed. If, on the other hand, you make changes to the source, then the visual display of your controls may also change. For instance, you can change the caption for the TextField controls in either the Inspector, or in the source for Applet1.java. In particular, changing the following line of code will yield visual results when you go back into Design mode.
For instance, if you change the text from "Add" to "JavaAdd," then the visual representation of the button in design mode will reflect that change. In fact, the version of the code you see in Design mode is a real rendering of the actual Java code. Its not a representation of what your applet will look like, it represents the actual appearance the form will have, because real Java objects are used to render it.
At this stage, it might be helpful to put your attention back on the Inspector again. Click on the Button component, and then look at the Inspector. Let's change the name of this component. If you look at your source code, you will see that the button is declared as follows:
Button button1 = new Button();
Now go back into design mode and use the Inspector to change the name of the button to addButton. If you switch to your source, you will see that you declaration now looks like this:
Button addButton = new Button();
The changed you made in design mode are reflected in your code! The same thing will occur if you change the text property for your control.
At this stage you are ready to start adding the necessary logic to your program to make it work. Remember that our goal is to allow the user to add two numbers together. First double click on the addButton to create an even handler for it. (Another way to make this happen is to go into the Inspector, turn to the Events page, and double click on the blank space to the right of the actionPerformed property.) When you are done, the following code should be pasted into your program:
.. // Code omitted here...
void addButton_actionPerformed(ActionEvent e)
{
// Your code goes here....
}
}
class Applet1_addButton_actionAdapter implements java.awt.event.ActionListener
{
Applet1 adaptee;
Applet1_addButton_actionAdapter(Applet1 adaptee)
{
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e)
{
adaptee.addButton_actionPerformed(e);
}
}
Just as I said in the last chapter, it is still not important that you understand what is happening here. You only need understand that you have to fill in the space between the curly braces in the actionPerformed method. The code you place between those braces is the code that will retreive the users input, then add up the numbers the user entered, and then send the results back to user.
Here is the code that you need to write:
void addButton_actionPerformed(ActionEvent e)
{
int Num1 = Integer.parseInt(textField1.getText());
int Num2 = Integer.parseInt(textField2.getText());
int Result = Num1 + Num2;
textField3.setText(Integer.toString(Result));
}
Let's take a moment to examine the code one line at a time. In Java, you need to declare the type of your variables. When a user enters something in a TextField, they are entering a string. A string is like a sentence. It includes written words. You can't add two words together, at least not to get the kind of results we want to create in this example. For instance, you can't add the words "Two" and "Two" together to get four. Nor can you add the letters "2" and "2" together to get 4. You might add them together to get something like this: "twotwo," or this "22," but that's not what we want to achieve.
What we need to do is first convert the string that the user enters into an integer, or into a Java type called an int. An integer is a whole number. It's not a floating point number like this: 2.2. Its a simple ordinal number that looks like this: 2.
NOTE: This is a bit confusing, so let me take a moment to try to clarify matters. An integer is a general term referring to what we usually call whole numbers. An int is a Java type that you can use when you want to manipulate whole numbers. You would use the word integer in spoken conversation, and you would use the type int in your Java programs. One is part of the code in your programs, the other is just a generic term for talking about whole numbers. To confuse the matter somewhat further, Java includes an object called an Integer. As you will see, the Integer object allows you to perform a number of useful operations on Integers, such as convert them into strings.
The first line of code you write looks like this:
Num1 =Integer.parseInt(textField1.getText());
This line of code converts a string into a number. Notice that it uses both the Integer object, and a variable of type int.
Suppose the user enters the string "2." This line of code will convert that string into the number 2. The engine that performs the task is found in the code fragment: Integer.parseInt(). All you need to do is pass in the string that you want to convert inbetween the paranthesis found at the end of the word parseInt. In turn for your efforts, Java will return you a number.
NOTE: This same code could be written like this:
String MyString = textField1.getText(); int Num1 = Integer.parseInt(MyString);
Syntactically, there is no difference between these two lines, and the single line of code I showed you earlier. They do the same things, and you should feel free to use whichever syntax is simplest for you to understand.
If the user passes in an invalid string, then Java will not be able to convert the string to a number. For instance, if instead of passing in the number "7", the user instead passes in "Seven", then Java won't be able to convert the users invalid input. Later in the text, I will explain how to handle that kind of problem. For now we will just ignore that kind of error.
NOTE: It is not yet time to fully explain the syntax of this line of code. For those experienced programmers who want a hint as to what is happening, I'll offer the following quick explanation. Java supports a class called Integer, and it has a static, or class method called parseInt. The parseInt method will convert a string to an integer, much as atoi works in C/C++, or as StrToInt works in Object Pascal.
The code shown here returns the result of the conversion into a variable of type int called Num1. Because Num1 is of type int, it can hold only integers. It cannot hold strings. You can, however, add two ints together to get the kind of result you seek. For instance, if the users sets Num1 to 3, and sets Num2 to 4, then the following line of code will set the variable Result to 7:
int Result = Num1 + Num2;
At this stage, we have the result that we the result that we want to display to the user, the only thing left to do is convert our integer back into a string and display it to the user. This task is performed by the following line of code:
textField3.setText(Integer.toString(Result));
In this case, we use the code Integer.toString to convert Result from an integer into a string. We can then pass the result of this to the setText method of the TextField, which will display the number to the user.
In review, here are the steps we took. First we converted the first number the user entered into a an integer:
int Num1 = Integer.parseInt(textField1.getText());
Then we converted the second number into an integer:
int Num2 = Integer.parseInt(textField2.getText());
Then we added the result together:
int Result = Num1 + Num2;
Finally we converted the result back into a string, and showed it to the user:
textField3.setText(Integer.toString(Result));
Note: The last line of code could have been rendered like this:
String MyString = Integer.toString(Result); textField3.setText(MyString);
At this stage, you have finished writing your second applet. The only thing you need to do now is run it. When you run it, you should find that you can enter in two numbers, add them together, and display the result.
In this chapter you have learned how to query the user for input, how to perform calculations on that input, and how to display the results of those calculations to the user. In the next chapter we will deploy our application on the web.