Created
October 12, 2020 15:54
-
-
Save sfinktah/e347371f24205c8343798ae40e9ee075 to your computer and use it in GitHub Desktop.
A slots and signals variation for ActionEvent/ActionListener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* A routing table for Observers and Observables. | |
* | |
* Effectively allows routing of an {@link ActionEvent}. Charmingly reminiscent | |
* of the classic "Signals and Slots" IPC mechanism, this allows the {@link ActionListener} | |
* to be linked to a previously registered (or yet-to-be registered) proxy ActionListener. | |
*/ | |
public class ActionRouter { | |
private final Map<String, ActionListener> actionRoutes = new HashMap<>(); | |
/** | |
* Register destination {@link ActionListener} (Observer) for {@code routeName} | |
* | |
* @param routeName key for this route | |
* @param listener destination listener for this route | |
* | |
* @see #createActionRoute(String) | |
*/ | |
public void acceptActionRoute(String routeName, ActionListener listener) { | |
synchronized (actionRoutes) { | |
actionRoutes.put(routeName, listener); | |
} | |
} | |
/** | |
* Register route (Observable) and return proxy {@link ActionListener} | |
* | |
* @param routeName key for this route | |
* | |
* @return a proxy ActionListener | |
* | |
* @see #acceptActionRoute(String, ActionListener) | |
*/ | |
private ActionListener createActionRoute(String routeName) { | |
if (!actionRoutes.containsKey(routeName)) { | |
synchronized (actionRoutes) { | |
actionRoutes.put(routeName, null); | |
} | |
} | |
return new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
if (actionRoutes.containsKey(routeName)) { | |
ActionListener listener = actionRoutes.get(routeName); | |
if (listener != null) { | |
listener.actionPerformed(e); | |
return; | |
} | |
JOptionPane.showMessageDialog(null, "Null route for: " + routeName, "CreateActionRoute", JOptionPane.INFORMATION_MESSAGE); | |
return; | |
} | |
JOptionPane.showMessageDialog(null, "No action route for: " + routeName, "CreateActionRoute", JOptionPane.INFORMATION_MESSAGE); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment