Event Processing for Swing component sets (4)

Source: Internet
Author: User

2.2.3 manage listener list
If we are creating our own components and want them to trigger events, we need to maintain a list of listeners to be notified. If the listener list is used for AWT events, we can use the AWTEventMulticaster class for list management. For the Swing library, if the event is not a predefined AWT event type, we need to manage the listener list by ourselves. By using the EventListenerList class in the javax. swing. event package, we no longer need to manually manage the listener list or worry about thread security. If we need to obtain the listener list, we can request the Component through public EventLIstener [] getListener (Class listenerType), or a type-specific method similar to the getActionListeners () method of JButton. This allows us to remove listeners from an internal management list to facilitate garbage collection.

AWTEventMulticaster class

Whether or not we realize that the AWTEventMulticaster class is used by the AWT component to manage the event listener list. This class implements all AWT Event Listeners (ActionListener, listener, ComponentListener, listener, FocusListener, listener, ItemListener, KeyListener, listener, MouseMotionListener, MouseWheelListener, TextListener, WindowFocusListener, windowListener and WindowStatListener ). AWTEventMulticaster is used as a support whenever we call the component method to add or remove a listener.

If we want to create our own components and manage the listener list for AWT event/listener pairs, we can use AWTEventMulticaster. As an example, let's take a look at how to create a common component. when the key is pressed inside the component, this component generates an ActionEvent object. This component uses the public static String getKeyText (int keyCode) method of KeyEvent to convert the key code to the corresponding text String, and return the text String as the ActionEvent Action Command. Because this component is the source of the ActionListener observer, it needs a pair of Add/Remove methods to handle listener registration. This is the use of the AWTEventMulticaster class, because it manages to add or remove listeners in our listener list variables:

Private ActionListener actionListenerList = null;
Public void addActionListener (ActionListener actionListener ){
ActionListenerList = AWTEventMulticaster. add (
ActionListenerList, actionListener );
}
Public void removeActionListener (ActionListener actionListener ){
ActionListenerList = AWTEventMulticaster. remove (
ActionListenerList, actionListener );
} The rest of the class definition describes how to handle internal events. An internal KeyListener must be registered to send a key to the ActionListener. In addition, the component must be able to obtain the input focus; otherwise, all the keys will reach other components. The complete class definition is shown in List 2-4. The code lines used for listener notifications are displayed in bold. This row notifies all registered listeners.

/**
*
*/
Package swingstudy. ch02;
 
Import java. awt. AWTEventMulticaster;
Import java. awt. Color;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. KeyAdapter;
Import java. awt. event. KeyEvent;
Import java. awt. event. KeyListener;
Import java. awt. event. MouseAdapter;
Import java. awt. event. MouseEvent;
Import java. awt. event. MouseListener;
 
Import javax. swing. JComponent;
 
/**
* @ Author lenovo
*
*/
Public class KeyTextComponent extends JComponent {
 
Private ActionListener actionListenerList = null;
 
Public KeyTextComponent (){
SetBackground (Color. CYAN );
KeyListener internalKeyListener = new KeyAdapter (){
Public void keyPressed (KeyEvent event ){
If (actionListenerList! = Null ){
Int keyCode = event. getKeyCode ();
String keyText = event. getKeyText (keyCode );
ActionEvent actionEvent = new ActionEvent (this, ActionEvent. action_receivmed, keyText );
ActionListenerList. actionreceivmed (actionEvent );
}
}
};
 
MouseListener internalMouseListener = new MouseAdapter (){
Public void mousePressed (MouseEvent event ){
RequestFocusInWindow ();
}
};
 
AddKeyListener (internalKeyListener );
AddMouseListener (internalMouseListener );
}
 
Public void addActionListener (ActionListener actionListener ){
ActionListenerList = AWTEventMulticaster. add (actionListenerList, actionListener );
}
 
Public void removeActionListener (ActionListener actionListener ){
ActionListenerList = AWTEventMulticaster. remove (actionListenerList, actionListener );
}
 
Public boolean isFocusable (){
Return true;
}
} Figure 2-5 shows all components. The above part is the component, while the bottom is a text input box. To display the text string that presses the key, an ActionListener is registered with the KeyTextComponent of the update text box.

The sample source code is shown in List 2-5.

/**
*
*/
Package swingstudy. ch02;
 
Import java. awt. BorderLayout;
Import java. awt. EventQueue;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
 
Import javax. swing. JFrame;
Import javax. swing. JTextField;
 
/**
* @ Author lenovo
*
*/
Public class KeyTextTester {
 
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
 
Runnable runner = new Runnable (){
Public void run (){
JFrame frame = new JFrame ("Key Text Sample ");
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
 
KeyTextComponent keyTextComponent = new KeyTextComponent ();
Final JTextField textField = new JTextField ();
 
ActionListener actionListener = new ActionListener (){
Public void actionreceivmed (ActionEvent event ){
String keyText = event. getActionCommand ();
TextField. setText (keyText );
}
};
 
KeyTextComponent. addActionListener (actionListener );
 
Frame. add (keyTextComponent, BorderLayout. CENTER );
Frame. add (textField, BorderLayout. SOUTH );
Frame. setSize (300,200 );
Frame. setVisible (true );
}
};
 
EventQueue. invokeLater (runner );
}
 
} EventListenerList class

Although the AWTEventMulticaster class is easy to use, it cannot be used to manage the list of Custom event Listeners or the swing event in javax. Swing. event. We can create a custom extension for this class to process the list of event listeners of every type that we need to manage, or we can store the list in a data structure such as Vector or sorted list. Although using Vector or sorted list can work well, we need to consider synchronization when using this method. If we do not write the List Management correctly, the listener notification may have an incorrect set of listeners.

To simplify this situation, the Swing Component Library contains a special event listening class, EventListenerList. An instance of this class can manage all different event listeners of a component. To demonstrate the usage of this class, let's take a look at how to replace AWTEventMulticaster with EventListenerList to rewrite the previous example. Note: In this particular example, using the AWTEventMulticaster class is actually a simpler solution. However, in a similar case, the event listener is not a predefined AWT event listener or we need to maintain multiple listener lists.

Adding or removing listeners is similar to the technology used by AWTEventMulticaster in the previous example. We need to create a suitable variable type-EventListenerList this time-and define the methods for adding and removing listeners. The main difference between the two methods is that the initial EventListenerList is not null, and the other is null at the beginning. First, you must create a reference to an empty EventListenerList. This avoids the need to check the null list variable multiple times later. The method for adding and removing listeners is also different. Because EventListenerList can manage any

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.