Question

How can I can draw with Graphics2D on the JGraphX graph? I tried something like this:

mxGraphComponent graphComponent = ...;
// ...
Graphics2D g = (Graphics2D)graphComponent.getGraphics();
g.setColor(Color.BLACK);
g.drawLine(0, 0, 500, 500);
graph.refresh();
graphComponent.refresh();
graphComponent.repaint();
Was it helpful?

Solution

First, graph.refresh(); will erase the dranw line since it will re-render all the graph on the graphics of the component.

Secondly, don't forget to call the draw function in the ADT Thread

final Graphics2D g = (Graphics2D)graphComponent.getGraphics();
Runnable r = new Runnable() {
   public void run() {
      g.setColor(Color.BLACK);
      g.drawLine(0, 0, 500, 500);
   }
};

if (!SwingUtilities.isEventDispatchThread()) {
    SwingUtilities.invokeLater(r);
} else {
    r.run();
}

Other than that, it should work normally as I have succesfully drawn rectangles on the component.

Note however that if the graph is zoomed or the scroll panes are not at the origin you will have to convert the points with :

    Point p = SwingUtilisties.convertPoint(graphComponent, x,y, 
              graphComponent.getGraphControl());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top