Example

A program example shall demonstrate the handling of ActionEvents. Two Buttons and a Label are created. An ActionListener is installed onto both Buttons, that ought to react to their activation by the user in form of altering the Labels' content.

Figure 2: The VoleEventHandlingExample

1    import jcontrol.ui.vole.Button;
2    import jcontrol.ui.vole.Frame;
3    import jcontrol.ui.vole.Label;
4    import jcontrol.ui.vole.event.ActionEvent;
5    import jcontrol.ui.vole.event.ActionListener;
6    
7    /**
8     * <p>This example demonstrates how to handle
9     * events within the GUI framework JControl/Vole.
10     * This program needs the image resource
11     * 'mouse.jcif'.</p>
12     *
13     * <p>(C) DOMOLOGIC Home Automation GmbH 2003-2005</p>
14     */
15    public class VoleEventHandlingExample
16                 extends Frame implements ActionListener {
17      // the Label
18      Label label;
19      // the right Button
20      Button button_right;
21    
22      /**
23       * Create two buttons and a label and add an ActionListener.
24       */
25      public VoleEventHandlingExample() {
26        // create the Buttons
27        Button b1 = new Button("Left Button", 2, 10, 60, 13);
28        button_right = new Button("Right Button", 66, 10, 60, 13);
29       
30        // add the ActionListener
31        b1.setActionListener(this);
32        button_right.setActionListener(this);
33       
34        // add the Buttons to the Frame
35        this.add(b1);
36        this.add(button_right);
37       
38        // create the Label
39        label = new Label("Please press a button!", 0, 30, 128, 10,
40                          Label.ALIGN_CENTER);
41        this.add(label);
42      }
43     
44     
45      /**
46       * This is the event handler. When a component fires an
47       * ActionEvent for us, this method is invoked.
48       */
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      }
62     
63    
64      /**
65       * Instantiate and show the main frame.
66       */
67      public static void main(String[] args) {
68        new VoleEventHandlingExample().show();
69      }
70    }
Listing 1: VoleEventHandlingExample.java