Page 698 - Introduction to Programming with Java: A Problem Solving Approach
P. 698
664 Chapter 16 GUI Programming Basics
After pressing Enter in the x box or clicking the Factorial button:
Figure 16.7 Sample session for the FactorialButton program Again from the createContents method:
}
xfBox.setText("undefined");
Apago PDF Enhancer
Listener listener = new Listener();
...
xBox.addActionListener(listener);
btn.addActionListener(listener);
Note that we’re registering the same listener with two different components. By doing this, we give the user two ways to trigger a response. The user can press Enter when the cursor is in the input text box (xBox) or the user can click on the button (btn). Either way causes the listener to react. Whenever you register the same listener with two different components, you need to have a name for the listener. That’s why we use a named inner class for this program (an anonymous inner class wouldn’t work).
Figure 16.8b’s actionPerformed method is chock full of interesting code. Of greatest importance is the Integer.parseInt method call. If you ever need to read numbers or display numbers in a GUI program, you have to use string versions of the numbers. Thus, to read a number from the input text box, we first read it in as a string, and then we convert the string to a number. To accomplish this, we read the string using xBox.getText(), and we convert it to a number using Integer.parseInt.
Ideally, you should always check user input to make sure it’s valid. In the actionPerformed method, we check for two types of invalid input—a non-integer input and a negative number input. Those inputs are invalid because the factorial is mathematically undefined for those cases. The negative number case is easier, so we’ll start with it. Note this code in the middle of the ActionPerformed method:
if (x < 0)
{