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()

2 comments:

Post a Comment