Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A slots and signals variation for ActionEvent/ActionListener
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