I recently asked a question about how to change the edge style under certain conditions.

However, that changes the entire style since setting the style in the model affects only the style name. When I load a graph I want to have e. g. a different color for the edge between vertices A and B. The edge (e. g. orthogonal, rounded) should remain intact, only 1 single attribute (e. g. color) of the style should be changed.

I figured you need to overwrite the view component. Is this correct or is there a better place? I thought I'd share my findings, maybe someone else needs this as well. See the code below.

asked 23 Mar '12, 23:21

Lofi's gravatar image

accept rate: 37%

edited 10 Aug '12, 15:46

David's gravatar image


Here's the code, just create a custom graph, overwrite createGraphView and there overwrite createState. My example paints the edge in the color of the source vertex's fill color:

public class MyGraph extends mxGraph {

  protected mxGraphView createGraphView()
    mxGraphView graphView = new mxGraphView(this) {
     public mxCellState createState(Object cell)
       if( ((mxCell) cell).isEdge()) {
          Map<String,Object> styleMap = graph.getCellStyle(cell);
          // we need to work on a clone; otherwise the style change
          // would affect all cells which use this style
          Map<String,Object> clonedMap = new HashMap<String,Object>();
          for( String key: styleMap.keySet())
            clonedMap.put( key, styleMap.get( key));
          // get color of source
          Map<String,Object> sourceStyleMap =  graph.getCellStyle( ((mxCell) cell).getSource());
          // the edge line color should be the fill color of the source vertex
          if( clonedMap != null && sourceStyleMap != null)
            clonedMap.put( mxConstants.STYLE_STROKECOLOR, sourceStyleMap.get( mxConstants.STYLE_FILLCOLOR));
          return new mxCellState(this, cell, clonedMap);
        return super.createState( cell);
    return graphView;
This answer is marked "community wiki".

answered 23 Mar '12, 23:28

Lofi's gravatar image

accept rate: 37%

edited 10 Aug '12, 15:52

David's gravatar image


Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported



Asked: 23 Mar '12, 23:21

Seen: 3,753 times

Last updated: 10 Aug '12, 15:52