Java Reference
In-Depth Information
Self-Test Exercises
36. What is the difference between an object of the class JTextArea and an object of
the class JTextField ?
37. What would happen if when running the GUI in Display 17.17 you were to enter
your name and click the "Click me" button three times?
38. Rewrite the program in Display 17.17 so that it uses a text area in place of a text field.
Change the label "Enter your name here:" to "Enter your story here:" . When
the user clicks the "Click me" button, your GUI should change the string displayed
in the text area to "Your story is " + lineCount + " lines long." . The vari-
able lineCount is a variable of type int that your program sets equal to the number
of lines currently displayed in the text area. Use a BorderLayout manager and place
your text area in the region BorderLayout.CENTER so that there is room for it. You
can assume the user enters at least one line before clicking the "Click me" button.
The last line in the text area will have no '\n' and so you may need to add one if you
are counting the number of occurrences of '\n' . Blank lines are counted.
TIP: Inputting and Outputting Numbers
When you want to input numbers using a Swing GUI, your GUI must convert input
text to numbers. For example, when you input the number 42 in a JTextField , your
program will receive the string "42" , not the number 42 . Your program must convert
the input string value "42" to the integer value 42 . When you want to output numbers
using a GUI constructed with Swing, you must convert the numbers to a string and
then output that string. For example, if you want to output the number 40 , your pro-
gram would convert the integer value 40 to the string value "40" . With Swing, all
input typed by the user is string input and all displayed output is string output. The
techniques for converting back and forth between strings and numbers were given in
Chapter 5 in the subsecton entitled “Static Methods in Wrapper Classes” and the Pro-
gramming Example entitled “Another Approach to Keyboard Input.” A simple exam-
ple of a Swing GUI with numeric input and output is given in the next subsection.
A Swing Calculator
Designing a realistic Swing calculator is one of the Programming Projects. In this pro-
gramming example, we will develop a simplified calculator to get you started on that
Programming Project. Display 17.19 contains a GUI for a calculator that keeps a run-
ning total of numbers. The user enters a number in the text field and then clicks either
the + or button. The number in the text field is then added into or subtracted from a
running total that is kept in the instance variable result , and then the new total, the
Search WWH ::




Custom Search