You will not actually write any code in this lesson. To simplify the tutorial, the action methods have been written for you. You will add them to your code by running the applet on this page.
- Click the Source Editor control
on the Java WorkShop tool bar.
The WorkShop opens the Source Editor with the file Calculator.java loaded. The file contains a template for your Calculator code. You need to add the following:
- The action method for the button call
- Code for figuring out which button the user clicks on
- Code that performs the action
- Code that updates the text label
- Type the path to your Calculator.java file in the box below and click the Copy button.
This step is specific to this tutorial. It copies a file that includes the code into your Calculator project directory, overwriting the existing Calculator.java file. This step has been included so you don't have to actually type in the code.
- Reload the Calculator.Java file in the Source Editor.
- Go to line 49, which contains the action method.
public boolean action (Message msg, Event evt, Object what)
The msg argument is of a special Visual Java type that contains all of the information about the action event. The evt
argument is a regular AWT event. It contains information about the event, such as the kind of event it was. The what argument is passed to the action command by AWT. It is not particularly useful for buttons, but for scrolling lists it might indicate when an item was selected.
- Look at lines 50 through 89.
These lines contain the code that figures out what button the user pressed. The target field of the msg argument is the object in which the event occurred. When you created the interface, you named the buttons b0, b1, b2, and so forth. The gui variable is the way to reference the objects in the GUI.
So, gui.b0 refers to the button that was named b0 when you created the interface.
Comparing the msg.target to these buttons tells you which button was pressed. Once the program determines which button was pressed, it calls a method which performs the button action. For example, if the user clicks button 7, the program calls the method number(7) (lines 94 through 104).
- Look at line 90.
gui.display.set("text", new Double(value).toString());
This line changes the text in the label (named display).