Doing without objectdrawTopKeyboard input

Keyboard input

The simplest way to enter data via the keyboard is to enter data in a JTextField GUI component. The program ColorMixer is similar to ColorSlider, but instead of selecting numbers using a JSlider, instead they are entered directly into a JTextField. In this particular case, we want to trigger an event whenever the user types a number and then hits the return key. Hitting the return key when typing in a JTextField triggers an ActionEvent, just like a JButton does.

The method Integer.parseInt(...) takes a string parameter and returns an int. Thus the code

    int mix = Integer.parseInt(stringValue);

converts stringValue to the corresponding int value.

See also the program Interesting, which calculates the interest on an investment.

The program TextApplet uses a TextArea. It is similar to a TextField except that it includes many lines of text and does NOT generate action events. You can either replace all text in the area using setText or add to the end with append. See the program for details.

Finally, the program 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.

Also, Java 7 doesn't seem to do a good job supporting applets with key events. To get the key strokes to be recognized I have to click on a different window than the applet and then click on the applet before anything is recognized.


Doing without objectdrawTopKeyboard input