Processing ActionEvents
The class ActionEvent
provides three methods to process received messages: getType()
, getActionCommand()
and getSource()
.
-
int getType()
: This method returns the type of the ActionEvent
as an int
. Table 1 lists the possible returned values:
Return Value | Description |
BUTTON_PRESSED | The message has been triggered by a Button . |
ITEM_SELECTED | An item of a List or ComboBox has been selected. |
VALUE_CHANGED | A numerical value has been changed (e.g. of a Slider ). |
STATE_CHANGED | The state of a RadioButtons or CheckBox has been changed. |
Table 1: Return values of method jcontrol.ui.vole.event.ActionEvent.getType()
-
String getActionCommand()
: Using the ActionCommand
, GUI components are able to add information to an ActionEvent
. The receiver can extract this information by invoking the method getActionCommand()
. The kind of information depends on the component. Button
s, for example, will transmit their labels. Notice that the ActionCommand
may also be null
.
-
Component getSource()
: With help of the method getSource()
, the source of an ActionEvent
can be determined. The return value represents a pointer to the appropriate Component
.
In the following excerpt of the example program are two techniques demonstrated of how to determine the source of an ActionEvents
. At first, the method onActionEvent
checks if the received event has been triggered by a Button
(event.getType()
). Thereafter shall be decided if the left or right Button
has been pressed. The left Button
is hereby identified by the methode event.getActionCommand
and the Button
's label. The right Button
is identified by using event.getSource()
. The last method may seem more elegant, but assumes the presence of a pointer to the Button
as a variable of the class instance. This may not be the case, if the ActionListener
is implemented by a separate class.
| ... |
| 49 public void onActionEvent(ActionEvent event) { |
| 50 // check whether this is a BUTTON_PRESSED event |
| 51 if (event.getType() == ActionEvent.BUTTON_PRESSED) { |
| 52 |
| 53 // recognize event's source by using getActionCommand() |
| 54 if (event.getActionCommand().equals("Left Button")) |
| 55 label.setLabel("You pressed the left button!", true); |
| 56 |
| 57 // recognize event's source by using getSource() |
| 58 if (event.getSource() == button_right) |
| 59 label.setLabel("The right button was hit!", true); |
| 60 } |
| 61 } |
| ... |
The kinds of ActionEvent
s that are generated by the components of JControl/Vole are described in the according API documentation. Indeed, all components provide the method setActionListener(ActionListener listener)
. That way, an application program may individually process the user triggered events and define, which events it will react to and which events will be ignored.
For more examples of how to process messages of GUI components, see the extensive documented program examples in section Examples & Demos.