COP3338 - Programming III

Florida International University (FIU)

School of Computer Science

COP3338 - Computer Programming III


Overview of Event Handling

The Event Hierarchy

Semantic Events

Low-Level Events

The Event Delegation Model


Overview of Event Handling

GUI applications are event-driven. User interaction such as with the GUI results in events being generated to inform the application of user interaction. Such interaction could be things such as: Events such as these can take place in any arbitrary order, and the application must be able to handle them when they occur.

Event handling in Java is based on the event-delegation model in which:

  1. Event classes encapsulate information about different types of user intereaction.
  2. Event source objects inform event listeners about events:
  3. Event listener objects that are informed by an event source when designated events occur, so that the event listener objects can take appropriate action.

The way that this model works can be divide into the following two sub-tasks:

Before implementing these two sub-tasks, lets's look at the event hierachy. Back to the top

The Event Hierarchy

The superclass of all events is java.util.EventObject. This class provides the method:

Object getSource() - that returns the object that generated the event.

Subclasses of this class are as follows:

The AWTEvent class is divided into two types of events. These are Semantic Events and Low-level Events.

Back to the top

Semantic Events

These classes represent user interaction with a GUI component. For example, clicking a button, selecting a menu item, scrolling, and changing text in a text filed or a text area. Semantic event classes are:

ActionEvent

AdjustmentEvent

ItemEvent

TextEvent

ActionEvent

This class is generated by by an action that is performed by any of the following components: This class provides the following method: String getActionCommand() . It returns the name associated with this action, such as a button label, a menu-item name, a list item name, or text.

AdjustmentEvent

This event is generated when adjustments are amde to an adjustable component such as a scrollbar. This class provides the method int getValue(). It returns the current value designated by the adjustable component.

ItemEvent

This event is generated when an item is selected or deselected in an item selectable component. These components are as follows: The class provides the method Object getItem() - It returns the object that was selected or deselected from the list. The label representeing the item is returned as a String object.

TextEvent

This event is generated whenever the content of a text component is changed The subclasses for the the TextComponent/JTextComponent class are:

Low-Level Events

These classes are used to represent low-level input or window operations. A single semantic event can constitute several low-level events. For example, clicking a button is actually a sequence of mouse movements followed by pressing and releasing a mouse button. Low-level event classes are:

ComponentEvent

ContainerEvent

FocusEvent

KeyEvent

MouseEvent

PaintEvent

WindowEvent

ComponentEvent

This event is generated when a component is hidden, shown, moved, or resized. These activities are handled internally by theAWT, and are normally not directly dealth with by the application. In other words, these events are generated by the Component class and its subclasses. The ComponentEvent class provides the following method: Component getComponent() .

ContainerEvent

This event is generated when a component is added or removed from a container. Similar to the ComponentEvent class, the events are handled internally by the AWT, and are normally not directly handled by the application.

FocusEvent

This event is generated when a component gains focus or loses focus. Gains focus means that the component can recieve keystrokes. For instance, if a button gains focus, the visual appearance is a rectangle around its border; a text field can have a blinking cursor. The method getId() inherited from AWTEvent can be used to determine the state of the component. The class provides the following constants:
  • FOCUS_GAINED
  • FOCUS_LOST.

    KeyEvent

    The class KeyEvent is a subclass of InputEvent class. This event is generated when the user presses or releases a key when typing characters.

    The class provides the following constants:

  • KEY_TYPED - This event is delievred when the key has been typed on the keyboard
  • KEY_PRESSED This event is delievred when the key is pressed
  • KEY_RELEASED This event is delievred when the key is released

    The inherited method getId() returns the specific type of event denoted by one of the constants.

    The class also provides the following methods:

  • char getKeyChar() - returns the keyboard key that was pressed
  • int getKeyCode() - returns the integer representation of the key

    MouseEvent

    This class, like KeyEvent is a subclass of InputEvent class. This event is generated when the user moves the mouse or presses the mouse button.The exact action is identified by the following constants:
  • MOUSE_CLICKED .
  • MOUSE_PRESSED .
  • MOUSE_RELEASED .
  • MOUSE_MOVED .
  • MOUSE_DRAGGED .
  • MOUSE_ENTERED .
  • MOUSE_EXITED .

    In addition to the inherited method getId(), the class provides the following methods:

  • int getX()
  • int getY()
  • Point getPoint()
  • void translatePoint(int, int)
  • int getClickCount() - returns the number of mouse clicks associated with the event.

    PaintEvent

    This event is handled internally by AWT. It is generated when a component should have its paint()/b> update() methods called.

    WindowEvent

    This event is generated when an operation is performed on a window. These operations are identified by the following constants in the WindowEvent class. The exact action is identified by the following constants:
  • WINDOW_OPENED .
  • WINDOW_CLOSING .
  • WINDOW_CLOSED .
  • WINDOW_ICONIFIED .
  • WINDOW_DEICONIFIED .
  • WINDOW_ACTIVATED .
  • WINDOW_DEACTIVATED .

    In addition to the inherited method getId(), the class provides the following method:

  • Window getWindow()

    Back to the top

    The Event Delegation Model

    As was mentioned, the AWT events are represented by subclasses of the java.awt.AWTEvent class. Note the following:

    Semantic Event Handling

    Event TypeEvent SourceListener Registration & Removal Methods provided by the source Event Listener Listener Interface implemented by a Listener
    ActionEvent
  • Button/JButton
  • List/JList
  • MenuItem/JMenuItem
  • TextField/JTextField
  • addActionListener(...)
  • removeActionListener( ... )
  • ActionListener
    AdjustmentEvent Scrollbar/JScrollbar
  • addAdjustmentListener(...)
  • removeAdjustmentListener( ... )
  • AdjustmentListener
    ItemEvent
  • Choice
  • List/JList
  • Checkbox/JCheckbox
  • CheckboxMenu/JCheckboxMenu
  • List/JList
  • addItemListener(...)
  • removeItemListener( ... )
  • ItemListener
    TextEvent
  • TextArea/JTextArea
  • TextField/JTextField
  • addTextListener(...)
  • removeTextListener( ... )
  • TextListener
    
    Given the following interface:
    
    
         public interface constants
         {
             String button[] = {"Write", "Draw", "Paint", "Print"},
         }
    
         import javax.swing.JFrame;
         import javax.swing.JButton;
         import javax.swing.ImageIcon;
         import java.awt.Container;
         import java.awt.GridBagLayout;
         import java.awt.GridBagConstraints;
    
         public class myJButton extends JButton implements constants
         {
            myJFrame f;
    
            JButton source;
    
            myJButton(myJFrame f)
            {
               this.f = f;
            }
    
            public void addButtons()
            {
                // 1. Get the contentPane for the frame myJFrame
                Container content = f.getContentPane();
    
               // 2. Create an object of the class GridBaglayout
               GridBagLayout gbag = new GridBagLayout();
    
               // 3. Set the layout manager for the container
                content.setLayout(gbag);
    
               // 4. Create an object of the class GridBagConstraints
               GridBagConstraints constraints = new GridBagConstraints();
    
               // 5. Layout each component
    
               constraints.fill = GridBagConstraints.NONE;
    
               for (int i = 0; i < button.length; i++)
               {
    
                   switch(i)
                   {
                       case 0:
                       {
                             source = new JButton(button[i]);
                            constraints.gridx = 0;
                            constraints.gridy = 1;
                            constraints.weightx = 0.5;
                            constraints.gridwidth = 1;
                            constraints.gridheight = 1;
                            break;
                      }
                      case 1:
                      {
                        // Set constraints
                          break;
                      }
                      case 2:
                      {
                          source = new JButton(button[i], new ImageIcon("Firewks1.jpg"));
                        // Set constraints
                         break;
                      }
                      case 3:
                      {
                          source = new JButton(button[i]);
                         // Set constraints
                      }
                 }
                 gbag.setConstraints(b, constraints);
                 content.add(b);
    
                 // Register each button object
                  source. addActionListener(new myActionListener(i));
            }
        }
    }
    
    

    Semantic Event Listeners and their Methods

    Event Listener InterfaceEvent Listener Methods
    ActionListener actionPerformed( ActionEvent e)
    AdjustmentListener adjustmentValueChanged( AdjustmentEvent e)
    ItemListener itemStateChanged(ItemEvent e)
    TextListener textVakueChanged( TextEvent e)
    
    // 3. ActionListener - Typical usage:
    
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener; // Contains actionPerformed(...)
    
    public class myActionListener implements ActionListener, constants
    {
         int i;
    
         public myActionListener(int i)
         {
            this.i = i;
         }
    
         public void actionPerformed(ActionEvent e)
         {
            if (button[i].equals(e.getActionCommand()))
              System.out.println(button[i] + " was pressed");
        }
    }
    
     Back to the top
    

    Low-level Event Handling

    Event TypeEvent SourceListener Registration & Removal Methods provided by the source Event Listener Listener Interface implemented by a Listener
    ComponentEvent Component/JComponent
  • addComponentListener(...)
  • removeComponentListener( ... )
  • ComponentListener
    ContainerEvent Container
  • addContainerListener(...)
  • removeContainerListener( ... )
  • ContainerListener
    FocusEvent Component/JComponent
  • addFocusListener(...)
  • removeFocusListener( ... )
  • FocusListener
    KeyEvent Component/JComponent
  • addKeyListener(...)
  • removeKeyListener( ... )
  • KeyListener
    MouseEvent Component/JComponent
  • addMouseListener(...)
  • removeMouseListener( ... )
  • addMouseMotionListener(...)
  • removeMouseMotionListener( ... )
  • MouseListener
    WindowEvent Window
  • addWindowListener(...)
  • removeWindowListener( ... )
  • WindowListener

    Semantic Event Listeners and their Methods

    Event Listener InterfaceEvent Listener Methods
    ComponentListener
  • componentHidden(ComponentEvent e)
  • componentMoved(ComponentEvent e)
  • componentResized(ComponentEvent e)
  • componentShown(ComponentEvent e)
  • ContainerListener
  • componentAdded(ComponentEvent e)
  • componentRemoved(ComponentEvent e)
  • FocusListener
  • FocusGained(FocusEvent e)
  • FocusLost(FocusEvent e)
  • KeyListener
  • keyPressed(KeyEvent e)
  • keyReleased(KeyEvent e)
  • keyTyped(KeyEvent e)
  • MouseListener
  • mouseClicked(MouseEvent e)
  • mouseEntered(MouseEvent e)
  • mouseExited(MouseEvent e)
  • mousePressed(MouseEvent e)
  • mouseReleased(MouseEvent e)
  • MouseMotionListener
  • mouseDragged(MouseEvent e)
  • mouseMoveded(MouseEvent e)
  • WindowListener
  • windowActivated(WindowEvent e)
  • windowClosed(WindowEvent e)
  • windowClosing(WindowEvent e)
  • windowDeactivated(WindowEvent e)
  • windowIconified(WindowEvent e)
  • windowDeiconified(WindowEvent e)
  • windowOpened(WindowEvent e)
  • An event listener interface can contain more than one method. For example, the WindowListener interface has seven (7) methods. If such interface is implemented, then it is imperative that all the methods are coded, even though a source object might not be interested in all of the methods. The alternate way to handle this siutation is to provide empty body to those methods that are not of interest to the object. Luckly Java has provided these method in classes called Adapter classes. So, instead of implementing the interfaces you would extend the respective adapter class, and you would simply define the body for the method of interest.

    	    myJFrame source = new myJFrame(frameTitle);
    	    source.addWindowListener(new myWindowEvents());
    	    source.addKeyListener(new myKeyEvent());
    
    WindowAdapter -  Typical usage
    
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    class myWindowEvents extends WindowAdapter implements constants
    {
         public void windowClosing(WindowEvent e)
         {
             // Flush any buffer
             // Close any opened file(s)
             // Do necessary clean up activity, then
             System.exit(0);
         }
    
         public void windowClosed(WindowEvent e)
         {
             System.out.println("windowClosed: " + e);
         }
    
         public void windowOpened(WindowEvent e)
         {
            // Do any necesary initialization tasks before any further activity
           System.out.println("windowOpened: " + e);
         }
    
         public void windowActivated(WindowEvent e)
         {
              System.out.println("windowActivated: " + e);
         }
    }
    
    KeyAdapter - typical usage
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyAdapter;
         
    public class myKeyEvent extends KeyAdapter 
    {
         myKeyEvent(){}
    
         public void keyTyped(KeyEvent e)   //  Handle the key typed event
         {
             displayInfo(e, "KEY TYPED: ");
         }
    
         public void keyPressed(KeyEvent e)  	// Handle the key pressed event
         {
             displayInfo(e, "KEY PRESSED: ");
         }
    
         public void keyReleased(KeyEvent e)  // Handle the key released event
         {
             displayInfo(e, "KEY RELEASED: ");
         }
    
         private void displayInfo(KeyEvent e, String s)
         {
             String charString, keyCodeString;
    
             char ch = e.getKeyChar();
             int keyCode = e.getKeyCode();
    
    
             if (Character.isISOControl(ch))
    	         charString = "key character = (an unprintable control character)";
             else
    	         charString = "\n" + "key character = '" + ch + "'";
    
              keyCodeString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")";
    
              System.out.print(s +  "    " +  keyCodeString  + charString + "\n");
         }
    }
    
    

    Back to the top