Showing posts with label Handling Events in SWING. Show all posts
Showing posts with label Handling Events in SWING. Show all posts

Monday, February 13, 2012

Coding an event handler

Listeners represent each event they handle with a separate method. And each listener method takes an event parameter of the appropriate type.



For example, the actionPerformed method of the ActionListener interface takes an ActionEvent object as a parameter.
public void actionPerformed (ActionEvent e)
In the code example, the class implements the MouseListener's mouseClicked method, which takes a MouseEvent object as a parameter.
public void mouseClicked (MouseEvent e) {
  String search = frame.t.getText( );
  String searchField = frame.scribble.getText( );
  if ( (search != null) & (search != " ") ) {
    int i = searchField.indexOf (search);
    if (i == -1)
      frame.display.setText("Search string not found");
    else {
      frame.display.setText("Search string found");
      // Highlight the found search string
      frame.scribble.select(i, i + search.length( ) );
    }
  }
}
When you implement a listener interface, you must provide empty implementations for any of its methods that you do not want to use.

Consider the code that provides empty implementations for the four MouseListener methods it doesn't use.
public void mouseClicked (MouseEvent e) {
  String search = frame.t.getText( );
  String searchField = frame.scribble.getText( );
  if ( (search != null) & (search != " ") ) {
    int i = searchField.indexOf (search);
    if (i == -1)
      frame.display.setText("Search string not found");
    else {
      frame.display.setText("Search string found");
      // Highlight the found search string
      frame.scribble.select(i, i + search.length( ) );
    }
  }
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
Java provides an adapter for each interface that has more than one method. For example, the WindowListener interface has a corresponding adapter class that implements it. This is called WindowAdapter.

To handle and perform this kind of event, a WindowEvent must be passed to a WindowListener or WindowAdapter object that is registered to a Window component.

The sample code shows how this is performed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SampleS {
    public static void main(String args[]) {
        JFrame f=new JFrame("Sample JFrame");
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void  windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
The addWindowListener method is used to register a WindowEvent for a Window component such as a JFrame. A windowClosing method is implemented whenever a WindowEvent occurs. This in turn closes the current window as executed by the System.exit(0) statement.
Using the adapter instead of the listener interface to handle an event often prevents you having to implement irrelevant methods that are part of the listener interface.

However, the downside is that by extending adapter classes, you prevent the event handler from extending any other class.

Supplement

Selecting the link title opens the resource in a new browser window.
View a table of listener interfaces and their adapters.
Event adapters and event listeners are commonly implemented using Java's anonymous inner classes. This allows you to register and define the event handling code all in one place and with the minimum of extraneous code.
checkBox.  {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
You can, for example, create an anonymous inner class that implements the ActionListener interface. To do this, you use a listener registration method - in this case, addActionListener - to register the adapter.
checkBox.MISSING CODE {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
component.addXXXListener (new XXXListener() {
  public void eventhandler (eventtype e) {
    // implementation   }
}
checkBox.addActionListener (new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
You type addActionListener (new ActionListener() to register the adapter.
You have registered the ActionListener anonymous class.

Next, you define the relevant method - in this case, actionPerformed.
checkBox.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    if (checkBox.isSelected())
      label.setText("You will be receiving special deals");
    else
      label.setText("You have chosen not to receive special deals");
  }
}
Suppose you have a List control and you add a listener to listen for ItemEvents. The listener implements the ItemListener interface, which contains one method only - the itemStateChanged method.
public void itemStateChanged (ItemEvent e)
The itemStateChanged method is invoked when the event occurs, such as when a list item is selected. The details of the event are passed to the event handler - in other words the method - via the ItemEvent argument, AccountList.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText();
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
The target object implements the ItemListener interface and is passed to ItemEvent when the event occurs. The listener is spared the details of processing individual mouse movements and mouse clicks, and instead processes semantic events, such as ItemEvent.DESELECTED or ItemEvent.SELECTED.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText()
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
The getItem method of the AccountList object is cast to a List datatype, which is assigned to target, an object of the List class.
public Object getItem()
The getItem method returns the element of the selectable control - a List in this example - affected by the selection event.
public void itemStateChanged(ItemEvent AccountList) {
  try {
    List target = (List) AccountList.getItem() ;
    int i = 0;
    while (i<6 && !(accountOptions[i].equals(target.getText()))) {
          i++;
    }
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      descriptions[i] = description.getText();
    }
    if (e.getStateChange() == ItemEvent.SELECTED) {
      description.setText(details[i]);
    }
  }
}
You can use the getPoint method in the MouseEvent object to determine an event's x and y coordinates. The returned coordinates are relative to the component's x and y coordinates. You can call getPoint() at any time.

Alternatively, you can call the getX and getY methods separately.
public synchronized Point getPoint()

public int getX()

public int getY()

Implementing an event listener

To code an event handler you need to

  • declare an event handler class
  • register an instance of the class as a listener on an event source
  • include code to implement the methods
You declare an event handler class by implementing a listener interface or by extending a class that does.
Because Java allows multiple interface implementations, it's possible for a single class to implement more than one listener interface. This feature allows you to use the same class to handle different types of events.
In the example, the SearchButton class implements the MouseListener interface, so that it is capable of handling mouse events, such as mousePressed or mouseClicked.
class SearchButton extends Button implements MouseListener {
  Gui3 frame; // Refers to the parent window
  SearchButton(String caption, Gui3 frame) {
    super (caption);
    this.frame = frame;
    addMouseListener(this);
  }
}
Once you have declared the event handler class, you need to register the listener. When listeners are registered on an event source, the Java runtime system automatically invokes the correct method in the listener in response to events, using a method call from the event source.
component.addeventlListener(theListener);
Each component has a set of methods available for registering listeners - one for each event type.

In the code example, the SearchButton class registers itself to listen for mouse events using the addMouseListener method.
class SearchButton extends Button implements MouseListener {
  Gui3 frame; // Refers to the parent window
  SearchButton(String caption, Gui3 frame) {
    super (caption);
    this.frame = frame;
    addMouseListener(this);
  }
}

The AWTEvent class

All events are instances of event classes in the event class hierarchy. All classes in this hierarchy inherit from the java.util.EventObject class, and all classes in the AWT event hierarchy inherit from java.awt.AWTEvent.

The subclasses of AWTEvent can be divided into two groups:
  • low-level events
  • high-level (or semantic) events
low-level events
Low-level events are very specific user actions, such as clicking a button or moving a mouse.
high-level (or semantic) events
High-level, or semantic, events are more generalized or abstract events. They occur when a user chooses, selects, or alters something. High-level events are also known as semantic events because they abstract meaningful actions from sets of lower-level actions.
The ComponentEvent class contains five subclasses representing low-level events. These are
  • InputEvent
  • WindowEvent
  • FocusEvent
  • ContainerEvent
  • PaintEvent
InputEvent
InputEvent is the root event class for all component-level input events. This class has two subclasses - MouseEvent and KeyEvent.

The three types of key events are key pressed, key released, and key typed. Each of these key events has a corresponding method and constant. You can use the getKeyChar method to return the char representing the key that has generated the event. Mouse events occur when a mouse button is pressed or released, or when a mouse is moved. The MouseEvent class also contains the MouseWheelEvent class for mouse wheel rotation.
WindowEvent
Window events occur whenever a window

  • is activated or deactivated
  • is opened, closed, or closing
  • is reduced to an icon or restored to a fully open state
  • gains or loses focus
FocusEvent
The two focus events are focus gained and focus lost. A component gains permanent focus when it makes a successful requestFocus method call or when users click or tab to access it. And it gains temporary focus as a side-effect of another operation, such as a window deactivation or scrollbar drag.

You distinguish between permanent and temporary focus using the isTemporary method of the FocusEvent:

public boolean isTemporary()

The isTemporary method returns true if the focus was temporarily lost.
ContainerEvent
Container events occur when components are added to, or removed from, a container.
The registered container listener receives notification of an event and can obtain the identity of the new component using a getChild method call. This allows containers to easily add input event listeners to, or remove them from, their components as each component is added or removed.
PaintEvent
Paint events are generated by the AWT, not delivered to any listeners. So they are of no practical use to programmers.
The four pre-defined subclasses representing semantic events are
  • ItemEvent
  • AdjustmentEvent
  • TextEvent
  • ActionEvent
ItemEvent
Item events occur in components that have implemented the ItemSelectable interface. They represent the selection or deselection events on selectable items, such as lists, checkboxes, and pop-up menus.

Item events are generated by ItemSelectable objects, for example Checkbox, List, JComboBox, and CheckboxMenuItem. Rather than having to deal with individual mouse or click events, this high-level event is more meaningful and a listener can more easily deal with relevant events.
AdjustmentEvent
Adjustment events occur in components such as scrollbars, which have numeric values that can be incremented or decremented by the user.

For example, as a scrollbar is moved, its new position is signaled to an adjustment listener as an adjustment event.
TextEvent
Text events occur when text is entered, deleted, or edited in text entry fields.
ActionEvent
Action events include such actions as clicking a button or pressing a function key. Several different user actions may result in the same action event being generated, which means that logically-related, higher-level events can be grouped together for handling in one place.

You can use the ActionEvent class's getActionCommand method to distinguish between different types of the same semantic event.
All event types are represented as predefined constants in the different event classes to which they belong. For example, the MouseEvent has constants for MOUSE_CLICKED and MOUSE_RELEASED, whereas for KeyEvent there are such constants as KEY_PRESSED.

You can use the AWTEvent class getID method to return one of these constants and so identify the type of event that has occurred.

Event delegation

It is important to consider how users interact with the user interface when designing a graphical user interface (GUI). The GUI may require users to click, resize, or drag and drop components of the interface, and input data using the keyboard. These actions will result to an event and you need to write a code to handle them.
Event handling code deals with events generated by GUI user interaction. The best practices for coding event handlers are outlined in the event delegation model.
The event delegation model comprises three elements:
  • Event source
  • Event listener
  • Adapter
Event source
An event source is a component, such as a GUI component, that generates an event. The event source can be generated by any type of user interaction. You can also combine a number of different types of events into one event object.

For example, if a user clicks and drags an icon, you can sum up the mouse-clicked event and the mouse-moved event into one event object.

In the event delegation model, a class represents each event type. Event objects are all defined in the java.util.EventObject subclasses.

A generated event object

  • provides the methods to add or remove the source event
  • manages the list of registered event listeners
  • provides the appropriate class type to the registered event listeners
Event listener
Event listeners are objects that receive notification of an event. Components define the events they fire by registering objects called listeners for those event types. When an event is fired, an event object is passed as an argument to the relevant listener object method. The listener object then handles the event.

To receive notification of an event, the object must be registered with the event source. To subscribe to the event source, you implement the appropriate listener interface.

All listeners are implementations of the EventListener interface or one of its subinterfaces. The Java API provides a predefined listener interface for each set of event types that a source can fire. For example, the MouseListener interface deals with mouse events, and the ActionListener interface deals with action events fired by buttons and other components.

Each listener interface provides at least one method for delivering the event object to the listener, in addition to any methods required for the action. All methods take one parameter and are part of the EventObject class.
Adapter
Adapters are abstract classes that implement listener interfaces using predefined methods. These are provided for convenience.

You can use an adapter to apply one listener's methods without having to implement all other methods. Adapters provide empty implementations for all interfaces' methods, so you only need to override the method you are interested in.
SwingWorker class is designed to be used for situations where you need to have a long running task run in a background thread and provide updates to the GUI either when done or while still in progress. Subclasses of SwingWorker must implement the doInBackground method to perform the background computation.
When using the SwingWorker class, you need to subclass SwingWorker and override the doInBackground method and done method. You can code a lengthy operation inside doInBackground and add another task into the done method before updating the Swing component from the event thread.
With the release of Java SE 6.0, additional features for sorting and filtering the JTable have been added. By filtering the contents of a JTable, only the rows that match the user specified constraints are displayed. Users can click on a specific column to be able to sort the contents accordingly.
Sorting is done by associating a JTable with a RowSorter class. RowSorter maintains two mappings. One maps rows in a JTable to the elements of the underlying model and the other let you go back again. Having two mappings allows you to do sorting and filtering. The class is generic enough to work with both TableModel and ListModel. TableRowSorter class is used to work with a JTable.
In the simplest case, you pass the TableModel to the TableRowSorter constructor and then pass the created RowSorter into the setRowSorter method of JTable.

The code shows an example:
           TableModel model = new DefaultTableModel(rows, columns) {
               public Class getColumnClass(int column) {
                   Class returnValue;
                   if ((column >= 0) && (column < getColumnCount())) {
                     returnValue = getValueAt(0, column).getClass();
                   } else {
                       returnValue = Object.class;
                   }
                   return returnValue;
             }
           };

           JTable table = new JTable(model);
           RowSorter<TableModel> sorter =new TableRowSorter<TableModel>(model);
           table.setRowSorter(sorter);
           JScrollPane pane = new JScrollPane(table);
           frame.add(pane, BorderLayout.CENTER);
           frame.setBounds(400, 350, 300, 225);
     frame.setResizable(false);   
           frame.setVisible(true);
       
     }
}
To perform filtering on a JTable, a RowFilter needs to be associated with the TableRowSorter and use it to filter the contents of a table using the include method.

The syntax for the include method is:
boolean include(RowFilter.Entry<? extends M,? extends I> entry)
For each entry in the model associated with the RowSorter, the method indicates whether the specified entry should be shown in the current view of the model. In many cases, you don't need to create your own RowFilter implementation.
In the given example, we use the regexFilter() method which uses a regular expression for filtering.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;

   public class SampleFilterJTable {
     public static void main(String args[]) {
           JFrame frame = new JFrame("Sorting JTable");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           Object rows[][] = {
             {"CLSRE", "Callinsure", 388.44},
                    {"INTRSW", "Inter-Swift", 12.56},
                    {"BRCD", "Brocadero", 57.13},
                    {"MIMPS", "Med-Imps", 32.52},
                    {"CBCO", "Custom Boat Co.", 443.26},
                    {"SETLS",  "Sharp-End Tools", 12.90},
                     {"PHLX", "Phlogistix", 31.25},
               {"MTLD", "Mathemetric Ltd.", 45.89}
           };
           Object columns[] = {"Symbol", "Name", "Price"};
           TableModel model =
              new DefaultTableModel(rows, columns) {
             public Class getColumnClass(int column) {
               Class returnValue;
               if ((column >= 0) && (column < getColumnCount())) {