CS 051 | Fall 2011 |
The JTextField allows the user to input a text string that can be used by the program.
The class example
ColorMixer
is similar to our ColorSlider program, except that the user can
enter the color values with the keyboard instead of sliding a JSlider back and forth.
The JTextField implements ActionListener, which triggers the call to actionPerformed
when the user hits the return key.
JTextField objects store strings. Thus, when the user enters an integer, it is stored as
a String, and must be converted into a usable form. The Integer class contains special
methods that we can use, including the parseInt method, which takes a String
as a parameter, and tries to convert it into an integer.
For example, the code Integer.parseInt("44") would be return the int value 44.
WARNING: Be careful when using this method because if the user enters a string that cannot be
converted, such as "four," then the parseInt method will crash the program. (In actuality,
the parseInt method will "throw an exception." We haven't talked about what this means
yet, or how to handle it, but will get to it soon.)
The class example
Interesting
also uses JTextField objects, but with some new twists.
We saw how we could use the setEditable method of JTextField objects to prevent
the user from changing the text in that field. We also saw the Double class, and its
parseDouble method, which is analogous to the Interger.parseInt method.
The class example
TextApplet
introduced a new object called JTextArea, which can hold
text, but which does not trigger an action event. We can append text to the text
already in a JTextArea, as well as setText to some value. We placed our
JTextArea inside a JScrollPane, then placed the JScrollPane on the
contentPane. This provided nice vertical and horizontal scroll bars when the text
in the JTextArea grew too big for the display.
The class demo
KeyDemo
demonstrates how to pick up keypresses in a program.
[Nothing will show up in this demo on the web because all of the output is through
System.out.println.] The KeyListener interface includes three methods, keyPressed,
keyTyped, and keyReleased, so all three must be included in any program implementing
KeyListener, even if only one of them is needed. The others may be given an empty body.
If you run this program someplace where the output is visible, you will notice some funny
behavior. Basically you should only depend on the method keyPressed for extracting info
on which key was pressed.