2016-04-15 59 views
1

我目前正在嘗試將JGraph 5應用程序遷移到JGraphX。我將頂點渲染器實現爲具有複雜佈局的嵌套JComponentVertex renderered as JComponent

使用mxStylesheet是我發現迄今爲止唯一定製vertext渲染。 JGraphX中有渲染器的概念嗎?是否有可能將渲染器實現爲JComponents

回答

2

我在CustomCanvas.java JGraphX示例中找到了答案。

此示例適用於非複合組件(JLabel ...),但複合組件失敗。 paintComponent()方法是爲父級調用的,但不是爲子級調用的。這似乎與CellRendererPane這個樣本中沒有父項的事實有關。添加到graphComponent的CellRendererPane解決了這個問題(對我來說,畫布是自然的父類,但它似乎不是一個容器)。

,則回答我原來的問題是:沒有,JGraphX不適合渲染器提供支持,但似乎你可以通過繼承兩個mxGraphmxGraphComponentmxInteractiveCanvas自己添加這種支持。

最後,這個示例可以很容易地擴展,以更常用的方式實現「渲染器」模式。我沒有引入渲染器工廠來縮短代碼片段,但這可能是有道理的。

public class SwingCanvas<USER_OBJECT> extends mxInteractiveCanvas { 
    private final CellRendererPane rendererPane = new CellRendererPane(); 
    protected mxGraphComponent graphComponent; 

    public SwingCanvas(SwingMxGraphComponent<USER_OBJECT> graphComponent) { 
     this.graphComponent = graphComponent; 
     graphComponent.add(rendererPane);  
    } 

    public void drawVertex(mxCellState state, String label) { 
     SwingMxGraph<USER_OBJECT> graph = graphComponent.getGraph(); 
     VertexRenderer<USER_OBJECT> vertexRenderer = graph.getVertexRenderer(); 
     USER_OBJECT userValue = (USER_OBJECT)((mxCell)state.getCell()).getValue(); 
     JComponent rendererComponent = vertexRenderer.getRendererComponent(graphComponent.getGraph(), userValue); 
     rendererPane.paintComponent(g, rendererComponent, graphComponent, 
      (int) state.getX() + translate.x, 
      (int) state.getY() + translate.y, 
      (int) state.getWidth(), (int) state.getHeight(), true); 
    } 
} 

public interface VertexRenderer<USER_OBJECT> { 
    /* Provide graph instance just in case...*/ 
    JComponent getRendererComponent(mxGraph graph, USER_OBJECT userObject); 
} 

public class SwingMxGraph<USER_OBJECT> extends mxGraph { 
    private VertexRenderer<USER_OBJECT> vertexRenderer; 

    /* Add the same method override as in sample 
    ... 
    ... */ 

    public VertexRenderer<USER_OBJECT> getVertextRenderer() { 
     return vertexRenderer; 
    } 
}