EVENT LISTENER LIST.
EVENT LISTENER LIST.
The EventListenerList class is defined in the javax,swing.event package. An EventListernerList is an array of XXEvent/XXListener pairs. JComponent and each of its descendants use an EventListenerList to maintain their listeners. All default models also maintain listeners and an EventListenerList.
On adding a listener to a swing component or model, the associated event's Class instance (used to identify event type) is added to its EventListenerList array followed by the listener itself.
Since these pairs are stored in an array rather than a mutable collection, a new array is created on each addition or removal using the System.arrayCopy() methods.
When events are received, the list is walked through and events are sent to each listener with a matching type. Because the array is ordered in an XXEvent, XXListener, YYEvent, YYListener fashion, a listener corresponding to a given event type is always next in the array. This gives for very efficient event-dispatching routines.
For thread safety, the methods for adding and removing listeners from an event listener synchronises access to the array when it is manipulated.
In JComponent, the EventListenerList is a protected field called listenerList so that all subclasses inherit it and most listeners are managed through listenerList.
Here is a code where the class itself handles the event and is the sole occupant of the component's event listener list.
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.lang.*;
public class Property extends JPanel implements ActionListener{
JButton jButton1 = new JButton(" ");
JTextField jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);
//this object is its own action listener
jButton1.addActionListener(this);
jText = new JTextField("welcome", 50);
add(jText);
}
private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
//get the action listeners associated with this object, here one
ActionListener[] al = jButton1.getActionListeners();
jText.setText("the "+al[0].getClass().toString()+" is the action listener " +
"in the list");
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

No comments:
Post a Comment