!7 lib 1007175 // mxGraph import com.mxgraph.model.mxCell; import com.mxgraph.util.mxPoint; import com.mxgraph.view.mxGraph; p { Frame.main(args); } /** * The frame example uses the graph model API to programmatically create * a graph image to be used as a background of a JComponent. */ static class Frame extends JFrame { /** * */ private static final long serialVersionUID = -578683911307318455L; /** * */ private GraphControl graphControl; /** * */ public Frame() { super("mxGraph"); // Creates graph with model mxGraph graph = new mxGraph(); Object parent = graph.getDefaultParent(); graph.getModel().beginUpdate(); try { Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80, 30); mxCell v2 = (mxCell) graph.insertVertex(parent, null, "World!", 240, 150, 80, 30); Object e1 = graph.insertEdge(parent, null, "e1", v1, v2); mxCell v3 = (mxCell) graph.insertVertex(e1, null, "v3", -0.5, 0, 40, 40, "shape=triangle"); v3.getGeometry().setRelative(true); v3.getGeometry().setOffset(new mxPoint(-20, -20)); } finally { graph.getModel().endUpdate(); } // Creates a control in a scrollpane graphControl = new GraphControl(graph); JScrollPane scrollPane = new JScrollPane(graphControl); scrollPane.setAutoscrolls(true); // Puts the control into the frame getContentPane().setLayout(new BorderLayout()); getContentPane().add(scrollPane, BorderLayout.CENTER); setSize(new Dimension(320, 200)); } /** * */ public static void main(String[] args) { Frame frame = new Frame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } import com.mxgraph.util.mxCellRenderer; import com.mxgraph.util.mxEvent; import com.mxgraph.util.mxEventObject; import com.mxgraph.util.mxEventSource.mxIEventListener; static class GraphControl extends JComponent { /** * */ private static final long serialVersionUID = -7470544285363165479L; mxGraph graph; Icon buffer; public GraphControl(mxGraph graph) { this.graph = graph; this.graph.getModel().addListener(mxEvent.CHANGE, new mxIEventListener() { public void invoke(Object source, mxEventObject evt) { GraphControl.this.graphModelChanged(); } }); } public mxGraph getGraph() { return graph; } public void paint(Graphics g) { super.paint(g); paintBuffer(g); } void paintBuffer(Graphics g) { Icon icon = getBuffer(); icon.paintIcon(this, g, 0, 0); } public Icon getBuffer() { if (buffer == null) { updateBuffer(); } return buffer; } protected void updateBuffer() { buffer = createBuffer(); int width = buffer.getIconWidth() + 1; int height = buffer.getIconHeight() + 1; Dimension d = new Dimension(width, height); if (!getPreferredSize().equals(d)) { setPreferredSize(d); revalidate(); } } protected Icon createBuffer() { return new ImageIcon(mxCellRenderer.createBufferedImage(graph, null, graph.getView().getScale(), null, true, null)); } protected void clearBuffer() { buffer = null; } public void refreshBuffer() { clearBuffer(); repaint(); } protected void graphModelChanged() { refreshBuffer(); } }