Listening to Selection Changes Efficiently
Tips & TricksSummary
Description
Listening to selection changes can easily be done by registering a Graph2DSelectionListener to the graph:
graph2D.addGraph2DSelectionListener(new Graph2DSelectionListener(){
public void onGraph2DSelectionEvent(Graph2DSelectionEvent e) {
//do something
}
});
But there is one problem using this approach:
Listening to every single selection change that happens might be quite inefficient if you want to react on all changes at once. For example when using the marquee selection and thus selecting various nodes, a selection event is beeing fired for every single node selection.
To avoid this you can use one of the following solutions:
Using helper class Selections.SelectionStateObserver
You can avoid this by registering an implementation of class Selections.SelectionStateObserver as a selection listener and graph listener:Graph2D graph2D = view.getGraph2D();
Selections.SelectionStateObserver listener = new Selections.SelectionStateObserver() {
protected void updateSelectionState(Graph2D graph) {
//handle all changes at once here
}
};
graph2D.addGraph2DSelectionListener(listener);
graph2D.addGraphListener(listener);
This helper class will bracket all changes and thus allows to handle all changes at once.
Simply add your code into method updateSelectionState of class SelectionsSelectionStateObserver.
Using SwingUtilities.invokeLater()
Another possibility is to wait for the marquee selection event to end and execute your selection handling code then. Therefor you can register a Graph2DSelectionListener to the graph as follows:Graph2D graph2D = view.getGraph2D();
graph2D.addGraph2DSelectionListener(
new Graph2DSelectionListener(){
List events;
protected Runnable runnable = new Runnable(){
public void run() {
List eventsCopy = events;
events = null;
onGraph2DSelectionEvents(eventsCopy);
}
};
public void onGraph2DSelectionEvent(Graph2DSelectionEvent e) {
if (events == null){
events = new ArrayList();
SwingUtilities.invokeLater(runnable);
}
events.add(e);
}
});
where onGraph2DSelectionEvents(List eventCopy) is the method where you can execute your code:
protected void onGraph2DSelectionEvents(List eventsCopy) {
System.out.println("SelectionStateObserverDemo.onGraph2DSelectionEvents");
for (Iterator iterator = eventsCopy.iterator(); iterator.hasNext();) {
Graph2DSelectionEvent event = (Graph2DSelectionEvent) iterator.next();
System.out.println("Selected " + event.getSubject());
}
}