01: /*
02: * Swing Explorer. Tool for developers exploring Java/Swing-based application internals.
03: * Copyright (C) 2008, Maxim Zakharenkov
04: *
05: * This program is free software; you can redistribute it and/or modify
06: * it under the terms of the GNU General Public License as published by
07: * the Free Software Foundation; either version 2 of the License, or
08: * (at your option) any later version.
09: *
10: * This program is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13: * GNU General Public License for more details.
14: *
15: * You should have received a copy of the GNU General Public License along
16: * with this program; if not, write to the Free Software Foundation, Inc.,
17: * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18: *
19: * $Header: /cvs/swingexplorer/src/org/swingexplorer/util/ListenerSupport.java,v 1.1 2008/03/07 11:46:53 maxz1 Exp $
20: */
21: package org.swingexplorer.util;
22:
23: import java.lang.reflect.InvocationHandler;
24: import java.lang.reflect.Method;
25: import java.lang.reflect.Proxy;
26: import java.util.ArrayList;
27:
28: /**
29: *
30: * @author Maxim Zakharenkov
31: */
32: public class ListenerSupport<L> {
33:
34: ArrayList<L> listeners;
35: Class listenerInterface;
36: L proxy;
37:
38: public ListenerSupport(Class _listenerInterface) {
39: listenerInterface = _listenerInterface;
40: }
41:
42: public void addEventListener(L l) {
43: if (listeners == null) {
44: listeners = new ArrayList<L>();
45: }
46: synchronized (listeners) {
47: listeners.add(l);
48: }
49: }
50:
51: public void removeEventListener(L l) {
52: if (listeners == null) {
53: return;
54: }
55: synchronized (listeners) {
56: listeners.remove(l);
57: }
58: }
59:
60: @SuppressWarnings("unchecked")
61: public L getDispatcher() {
62: if (proxy == null) {
63: proxy = (L) Proxy.newProxyInstance(this .getClass()
64: .getClassLoader(),
65: new Class[] { listenerInterface },
66: new InvocationHandlerImpl());
67: }
68: return proxy;
69: }
70:
71: class InvocationHandlerImpl implements InvocationHandler {
72: public Object invoke(Object proxy, Method method, Object[] args)
73: throws Throwable {
74:
75: Object[] arrListeners;
76: synchronized (listeners) {
77: arrListeners = listeners.toArray();
78: }
79: for (Object listener : arrListeners) {
80: method.invoke(listener, args);
81: }
82: return null;
83: }
84: }
85: }
|