Java Swing - O Reilly Here is a SecretLabel (Web site development)

Java Swing - O Reilly Here is a SecretLabel class that extends JLabel and fires ActionEvent messages when clicked. The label does not give any indication it has been clicked, hence its secret nature. The code for this label demonstrates how an EventListenerList is typically used. Figure 27.3 shows the SecretLabel up and running. Figure 27.3. A JLabel that uses an EventListenerList to facilitate dispatching events We set up the standard addActionListener() and removeActionListener() methods, which delegate to the listener list, and pass in the type of listener we’re attaching. (Recall that EventListenerList can store any type of listener.) When we actually fire an event, we search the listener list array, checking the even-numbered indices for a particular type of listener. If we find the right type (ActionListener, in this case) we use the next entry in the list as an event recipient. You can find other such examples throughout the Swing package in such models as DefaultTreeModel, DefaultTableModel, and DefaultButtonModel. The EventListenerList provides a generic dispatcher that works in just about every situation. However, it is not the only way to dispatch events. For a particular application you may find a more efficient means. // SecretLabel.java // An extension of the JLabel class that listens to mouse clicks and converts // them to ActionEvents, in turn are reported via an EventListenersList object. // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SecretLabel extends JLabel implements MouseListener { public SecretLabel(String msg) { super(msg); addMouseListener(this); } public void addActionListener(ActionListener l) { // We’ll just use the listenerList we inherit from JComponent listenerList.add(ActionListener.class, l); } public void removeActionListener(ActionListener l) { listenerList.remove(ActionListener.class, l); } public void mouseClicked(MouseEvent me) { fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, “SecretMessage”)); - 928
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Leave a Reply