Handling Mouse Events on Diagram Elements
Tips & TricksSummary
Description
Mouse Input Callbacks
In yFiles, the class ViewMode is responsible for all user interaction with the mouse.
In order to respond to mouse input events with a custom behavior, you can either subclass existing ViewModes like EditMode or NavigationMode or create your own ViewMode.
A ViewMode can either be added directly to the Graph2DView using Graph2DView.addViewMode(ViewMode) or be registered as a child mode of another ViewMode using ViewMode.setChild(y.view.ViewMode, java.awt.event.MouseEvent, java.awt.event.MouseEvent). Please see the Developers Guide for details about the ViewMode class.
There are two kinds of callback methods for handling mouse events in a ViewMode: those defined by the interface javax.swing.event.MouseInputListener and those receiving event coordinates already converted to world coordinates.
If you override one of the methods that receive a MouseEvent like e.g. mouseClicked(MouseEvent e), you have to convert the given event coordinates to world coordinates:
public void mouseClicked(MouseEvent e) {
double x = translateX(ev.getX());
double y = translateY(ev.getY());
System.out.println( "mouse clicked at "+x+","+y );
}
whereas when overrding e.g. mouseClicked(double x, double y), you can use the coordinates directly.
To retrieve the graph elements hit by a mouse event, you can use the methods ViewMode.getHitInfo(double x, double y), ViewMode.getHitInfo(MouseEvent ev), Graph2D.getHitInfo( double x, double y ) and Graph2D.getHitInfo( double x, double y, boolean firstHitOnly).
You can always access the current MouseEvents using the protected fields ViewMode.lastPressEvent, ViewMode.lastDragEvent, ViewMode.lastMoveEvent etc.
Example: React when a NodeLabel is double clicked
This example demonstrates how to determine when the user double clicks on a node label.
public class MyViewMode extends EditMode {
public void mouseClicked(double x, double y) {
MouseEvent ev = lastClickEvent;
if (ev.getClickCount() == 2) {
// we can't use ViewMode.getHitinfo(x,y) here, since otherwise
// HitInfo will stop looking for objects under x,y as soon as
// the first hit node is found - getHitNodeLabel() would return null
// if a label was clicked inside the node bounds.
HitInfo allHitObjects = getGraph2D().getHitInfo(x, y, false);
NodeLabel hitLabel = allHitObjects.getHitNodeLabel();
// do something with hitLabel..
} else {
// let EditMode handle the click event
super.mouseClicked(x,y);
}
}
}
For details on class HitInfo, see the knowledge base article How to determine the hit order of graph elements for mouse input".
See the StateNodeRealizerDemo for an example of a custom ViewMode that handles node clicks.