6.04 - Component Events


Introduction

At the moment we have displayed components, adding them to applications, and they work to the extent that you can press the buttons, select from the list etc., however they do not currently interact with your own code. If we want to use these components we must be aware of how the java.awt.event package classes work. Note that with events the structure is quite different from Java 1.1.x (Java 1) to Java 1.2+.x (Java 2). There are many reasons for this, but the main reason is that there were serious problems with the event structure of Java 1, especially in relation to threaded applications. We are only examining the event structure of Java 2+.

ActionEvent (java.awt.event.ActionEvent)

An ActionEvent object is generated by several of the components we have just discussed. A component such as a Button object generates an ActionEvent object when it is pressed. We also need to register a listener with the component so that we can direct the event to do something in our application. For a Button object we can do this using, for example:

  Button b = new Button("Test Button");
  b.addActionListener(this);

Where this refers to an object that is capable of handling the ActionEvent object that is passed to it. So in this case the class in which the Button b is defined must implement that ActionListener interface. So for a full example, use the following application:

Figure 6.16. Button Events Application


The application should display which button is pressed in the TextField as soon as the button is pressed. The source code for this example is below.

ButtonEvents.java

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
package ee402;

import java.awt.*;
import java.awt.event.*;

@SuppressWarnings("serial")
public class ButtonEvents extends Frame implements ActionListener{

                private Button button1, button2, button3;
                private TextField status;
                
                public ButtonEvents()
                {
                 super("Button Events");
                 this.setLayout(new FlowLayout());
                 status = new TextField(20);

                 this.button1 = new Button("Button 1");
                 this.button2 = new Button("Button 2");
                 this.button3 = new Button("Button 3");

                 this.button1.addActionListener(this);
                 this.button2.addActionListener(this);
                 this.button3.addActionListener(this);

                 this.add(status);
                 this.add(button1);
                 this.add(button2);
                 this.add(button3);
                
                 this.pack();
                 this.setVisible(true);
                }
                
                public void actionPerformed(ActionEvent e)
                {
                 if (e.getActionCommand().equals("Button 1"))
                 {
                 status.setText("Button 1 Pressed");
                 }
                 else if (e.getActionCommand().equals("Button 2"))
                 {
                 status.setText("Button 2 Pressed");
                 }
                 else
                 {
                 status.setText("Button 3 Pressed");
                 }
                }

                public static void main(String[] args) {
                        new ButtonEvents();
                }
}

Some notes about this code segment:

  • The java.awt.event package must be included to allow for the use of the ActionEvent and associated classes.

  • The application class must implement ActionListener to handle ActionEvents. Once our class uses the statement implements ActionListener then we must write a method public void actionPerformed(ActionEvent e). If we do not write this method then the code will not compile.

  • We must use the method addActionListener() to the component to state that this component generates events and to direct these events to a suitable object. In this application we use the keyword this which represents this object of the application. So we are sending the event to this object. We are only allowed to do that because this object implements ActionListener. If it did not then an error would be generated at compile time.

  • Once the event is sent to this object then the actionPerformed() method is called and it is passed an ActionEvent object - in this case called e. We can then interrogate this ActionEvent object to determine its source. In this application we have three different buttons that could have caused this object to be generated. One way of interrogating the ActionEvent object is to use its getActionCommand() method that returns the action command as a String object. In the API documentation it states that the action command for a Button object is the text on the surface of the button by default. We then use the equals() method of the String class that allows us to compare the action command to a String such as "Button 1". If the "Button 1" String is a perfect match then we set the text of the TextField to be "Button 1 Pressed" using the setText() method of the TextField object status.

Other Event Types

The ActionEvent class and the ActionListener interface mechanism can be used to deal with events on buttons and on other components also. The ActionEvent class deals with actions that can occur. Other events can be created by other components - how do we know which events are created by which components? Well you have to read the API documentation for that component. For the components we have looked at in this section:

Figure 6.17. Component Events

Component Events
  • Button objects generate an ActionEvent object when the mouse is pressed on the Button object. You can add a listener to the object by using the addActionListener()method that requires a listener object as a parameter. The Listener object must implement the ActionListener interface that requires an actionPerformed() method to be written.

  • Checkbox objects generates an ItemEvent object. You can add a listener to the object using the addItemListener() method that requires a listener object as a parameter. The listener must implement the ItemListener interface and is therefore required to write an itemStateChanged() method.

  • CheckboxGroup object is really a group of Checkbox objects and does not generate any events as a group, rather the individual objects generate the events as for Checkboxobjects. If you need to find out the individual Checkbox object that was chosen use the getSelectedCheckbox() method.

  • Choice objects generates an ItemEvent object. You can add a listener to the object using the addItemListener() method that requires a listener object as a parameter. The listener must implement the ItemListener interface and is therefore required to write an itemStateChanged() method.

  • Label objects do not generate events.

  • TextField objects generate KeyEvent objects when a key is pressed in the box. This KeyEvent object can be a key pressed, a key released or a key typed. You can use the addKeyListener() to add a listener to the TextField object. This method requires an object that has implemented the KeyListener interface that requires the object to implement the keyPressed(),keyReleased() and keyTyped() methods. A TextField object can also generate an ActionEvent object when the enter key is pressed in the text area. This ActionEvent has the same format as for the Button component above.

  • List objects generate an ItemEvent object when items are selected or deslected in the list. You can add a listener to the object using the addItemListener() method that requires a listener object as a parameter. The listener must implement the ItemListener interface and is therefore required to write an itemStateChanged() method. The Listobject also generates an ActionEvent object if the mouse is double-clicked or enter is pressed on an item in the list.

  • TextArea objects do not generate events.

  • Scrollbar objects generate an AdjustmentEvent object when the Scrollbar's bubble is moved. You can add a listener to the Scrollbar object by using the addAdjustmentListener() method that requires an object that implements the AdjustmentListener interface requiring the adjustmentValueChanged() method to be written.

The Component class can generate many event types. The Component is the parent of all visible AWT components, providing the template for all AWT components. It can have:

  • FocusEvent which notifies a FocusListener listener when the component has been selected.

  • ComponentEvent which notifies a ComponentListener listener when the component has been resized, moved or made visible/invisible.

  • HierarchyEvent which notifies a HierarchyListener when the hierarchy that this component belongs to changes. A component can be added to a container's hierarchy using the add() method as we have used for myPanel.add(new Label("test")); where myPanel is an object of the Panel class, thus is a Container object.

  • An InputMethodEvent which notifies a ComponentListener listener when the component has been re-sized, moved or made visible/invisible.

  • MouseEvent which notifies a MouseListener listener that the mouse has entered or exited the component, clicked or pressed/released the mouse button on the Componentobject.

  • MouseMotionEvent which notifies a MouseMotionListener listener when the mouse has been dragged or moved in the Component object area.

  • MouseWheelEvent which notifies a MouseWheelListener listener when the mouse wheel is rotated within the Component object area. The listeners mouseWheelMoved() method is called when the mouse wheel event occurs.

The TextComponent class can generate TextEvent objects. It has the Component class as its parent and so can generate the same events as above for Component. A TextEvent is generated when the object's text is changed.




These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
ċ
ButtonEvents.java
(1k)
Derek Molloy,
12 Nov 2013, 15:25
Comments