some update/refresh fixes
[fanfix.git] / src / be / nikiroo / fanfix_swing / gui / utils / ListenerPanel.java
1 package be.nikiroo.fanfix_swing.gui.utils;
2
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import java.util.LinkedList;
6 import java.util.Queue;
7
8 import javax.swing.JPanel;
9
10 import be.nikiroo.fanfix_swing.gui.SearchBar;
11
12 /**
13 * A {@link JPanel} with the default {@link ActionListener} add/remove/fire
14 * methods.
15 * <p>
16 * Note that it will queue all events until at least one listener comes (or
17 * comes back!); this first (or at least curently unique) listener will drain
18 * the queue.
19 *
20 * @author niki
21 */
22 public class ListenerPanel extends JPanel {
23 private static final long serialVersionUID = 1L;
24
25 private final Queue<ActionEvent> waitingQueue;
26
27 /**
28 * Create a new {@link ListenerPanel}.
29 */
30 public ListenerPanel() {
31 waitingQueue = new LinkedList<ActionEvent>();
32 }
33
34 /**
35 * Check that this {@link ListenerPanel} currently has {@link ActionListener}s
36 * that listen on it.
37 *
38 * @return TRUE if it has
39 */
40 public synchronized boolean hasListeners() {
41 return listenerList.getListenerList().length > 1;
42 }
43
44 /**
45 * Check how many events are currently waiting for an {@link ActionListener}.
46 *
47 * @return the number of waiting events (can be 0)
48 */
49 public synchronized int getWaitingEventCount() {
50 return waitingQueue.size();
51 }
52
53 /**
54 * Adds the specified action listener to receive action events from this
55 * {@link SearchBar}.
56 *
57 * @param listener the action listener to be added
58 */
59 public synchronized void addActionListener(ActionListener listener) {
60 if (!hasListeners()) {
61 while (!waitingQueue.isEmpty()) {
62 listener.actionPerformed(waitingQueue.remove());
63 }
64 }
65
66 listenerList.add(ActionListener.class, listener);
67 }
68
69 /**
70 * Removes the specified action listener so that it no longer receives action
71 * events from this {@link SearchBar}.
72 *
73 * @param listener the action listener to be removed
74 */
75 public synchronized void removeActionListener(ActionListener listener) {
76 listenerList.remove(ActionListener.class, listener);
77 }
78
79 /**
80 * Notify the listeners of an action.
81 *
82 * @param listenerCommand A string that may specify a command (possibly one of
83 * several) associated with the event
84 */
85 protected synchronized void fireActionPerformed(String listenerCommand) {
86 ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, listenerCommand);
87 if (hasListeners()) {
88 Object[] listeners = listenerList.getListenerList();
89 for (int i = listeners.length - 2; i >= 0; i -= 2) {
90 if (listeners[i] == ActionListener.class) {
91 ((ActionListener) listeners[i + 1]).actionPerformed(e);
92 }
93 }
94 } else {
95 waitingQueue.add(e);
96 }
97 }
98 }