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 WombatEventHandlingExample

1    import jcontrol.ui.wombat.Button;
2    import jcontrol.ui.wombat.Container;
3    import jcontrol.ui.wombat.Frame;
4    import jcontrol.ui.wombat.Label;
5    import jcontrol.ui.wombat.event.ActionEvent;
6    import jcontrol.ui.wombat.event.ActionListener;
7    
8    /**
9     * <p>This example demonstrates how to handle
10     * events within the GUI framework JControl/Wombat.
11     * This program needs the image resource
12     * 'mouse.jcif'.</p>
13     *
14     * <p>(C) DOMOLOGIC Home Automation GmbH 2003-2005</p>
15     */
16    public class WombatEventHandlingExample
17                 extends Frame implements ActionListener {
18      // the Label
19      Label label;
20      // the right Button
21      Button button_right;
22    
23      /**
24       * Create two buttons and a label and add an ActionListener.
25       */
26      public WombatEventHandlingExample() {
27        // create the Buttons
28        Button b1 = new Button("Left Button", 2, 10, 60, 13);
29        button_right = new Button("Right Button", 66, 10, 60, 13);
30       
31        // add the ActionListener
32        b1.setActionListener(this);
33        button_right.setActionListener(this);
34    
35      // create a content pane
36      Container content = new Container();
37        this.setContent( content);
38       
39        // add the Buttons to the Frame
40        content.add(b1);
41        content.add(button_right);
42       
43        // create the Label
44        label = new Label("Please press a button!", 0, 30, 128, 10,
45                    Label.STYLE_ALIGN_CENTER);
46        content.add(label);
47      }
48     
49      /**
50       * This is the event handler. When a component fires an
51       * ActionEvent for us, this method is invoked.
52       */
53      public void onActionEvent(ActionEvent event) {
54        // check whether this is a BUTTON_PRESSED event
55        if (event.type == ActionEvent.BUTTON_PRESSED) {
56         
57          // recognize event's source by using getActionCommand()
58          if ( "Left Button".equals(event.command))
59            label.setText("You pressed the left button!");
60           
61          // recognize event's source by using getSource()
62          if (event.source == button_right)
63            label.setText("The right button was hit!");
64        }
65      }
66    
67      /**
68       * Instantiate and show the main frame.
69       */
70      public static void main(String[] args) {
71        new WombatEventHandlingExample().setVisible(true);
72      }
73    }
Listing 1: WombatEventHandlingExample.java