NumberFields & Keyboard input |
The simplest way to enter data via the keyboard is to enter data in a TextField GUI component. The program ColorMixer allows the user to type numbers between 0 and 255 into a NumberField. (NumberFields differ from TextFields in that only numbers may be entered.) The three numbers are combined to form a new color, which is displayed in a rectangle filling the canvas. As with Choice items, the method onChangeDo is used to associate an action with user interaction that changes the number
The method asNumber is part of the String class. if the receiver is a text representation of a number then it will convert it to a number. If not, then it will treat it as 0. Thus the code
def mix: Number = stringValue.asNumber
converts stringValue to the corresponding numeric value.
See also the program Interesting, which calculates the interest on an investment.
Finally, the program KeyDemo demonstrates how to pick up keypresses in a program. Basically each key is associated with a code number. For example the left, up, right, and down arrow keys are associated with the codes 37, 38, 30, and 40, while the letters "a", "b", and "c" are associated with 65, 66, and 67.
Other methods associated with keys are onKeyRelease and onKeyTyped. Notice these are all methods on the application itself so their receiver is self (and thus usually omitted).
Finally we shown in program MoveBoxWKey how to move an object on the screen using the arrow keys.
NumberFields & Keyboard input |