Hello!
I'm looking for a straightforward way to make a Swing component forward all received events to its parent container (or even all parents up to root).
EDIT:
Where do I need this? I have a diagram editor. Components must forward key press and
mouse clicks (to set themselves as "active" as soon as the user clicks a subelement
of that component).
First, let me present my existing solution for this. It's a bit of a workaround.
public interface IUiAction {
void perform(Component c);
}
public static void performRecursiveUiAction(Container parent, IUiAction action) {
if (parent == null) {
return;
}
for (Component c : parent.getComponents()) {
if (c != null) {
action.perform(c);
}
}
for (Component c : parent.getComponents()) {
if (c instanceof Container) {
performRecursiveUiAction((Container) c, action);
}
}
}
/**
* 1) Add listener to container and all existing components (recursively).
* 2) By adding a ContainerListener to container, ensure that all further added
* components will also get the desired listener.
*
* Useful example: Ensure that every component in the whole component
* tree will react on mouse click.
*/
public static void addPermanentListenerRecursively(Container container,
final IUiAction adder) {
final ContainerListener addingListener = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
adder.perform(e.getChild());
}
};
// step 1)
performRecursiveUiAction(container, adder);
// step 2)
performRecursiveUiAction(container, new IUiAction() {
@Override
public void perform(Component c) {
if (c instanceof Container) {
((Container) c).addContainerListener(addingListener);
}
}
});
}
Usage:
addPermanentListenerRecursively(someContainer,
new IUiAction(
@Override
public void perform(Component c){
c.addMouseListener(somePermanentMouseListener);
}
)
);
By looking over the code, would you say it's a good concept?
The problem with my current concept is: It's forwarding only events, for which a listener was specified manually.
Can you suggest a better one?