Java Reference
In-Depth Information
TIP: Labeling a Text Field
Sometimes you want to label a text field. For example, suppose the GUI asks for a
name and a credit card number and expects the user to enter these in two text fields.
In this case, the GUI needs to label the two text fields so that the user knows in which
field to type the name and in which field to type the credit card number. You can use
an object of the class JLabel to label a text field or any other component in a Swing
GUI. Simply place the label and text field in a JPanel and treat the JPanel as a single
component. For example, we did this with the text field name in Display 17.17 .
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 fi eld. 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 variable 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' 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 program 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 subsection titled “Static Methods in Wrapper Classes”
and the Programming Example entitled “Another Approach to Keyboard Input.” A
simple example of a Swing GUI with numeric input and output is given in the next
subsection.
 
Search WWH ::




Custom Search