我从JUNG开始,我在新创建的JFrame的Jpanel中绘制图形,但是我无法在我正在开发的程序的现有Panel中绘制相同的Graph。
我使用的功能是:
private void demoGraph() {
// Graph<V, E> where V is the type of the vertices and E is the type of the edges
// Note showing the use of a SparseGraph rather than a SparseMultigraph
Graph<Integer, String> g = new SparseGraph<>();
// Add some vertices. From above we defined these to be type Integer.
g.addVertex((Integer) 1);
g.addVertex((Integer) 2);
g.addVertex((Integer) 3);
// g.addVertex((Integer)1); // note if you add the same object again nothing changes
// Add some edges. From above we defined these to be of type String
// Note that the default is for undirected edges.
g.addEdge("Edge-A", 1, 2); // Note that Java 1.5 auto-boxes primitives
g.addEdge("Edge-B", 2, 3);
// Layout<V, E>, VisualizationComponent<V,E>
Layout<Integer, String> layout = new CircleLayout(g);
layout.setSize(new Dimension(300, 300));
VisualizationViewer<Integer, String> vv = new VisualizationViewer<>(layout);
vv.setPreferredSize(new Dimension(350, 350));
// Setup up a new vertex to paint transformer...
Transformer<Integer, Paint> vertexPaint = new Transformer<Integer, Paint>() {
@Override
public Paint transform(Integer i) {
return Color.GREEN;
}
};
// Set up a new stroke Transformer for the edges
float dash[] = {10.0f};
final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
Transformer<String, Stroke> edgeStrokeTransformer = new Transformer<String, Stroke>() {
@Override
public Stroke transform(String s) {
return edgeStroke;
}
};
vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
// paint on a JPanel: NOT WORKING
GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
panel.setSize(this.graphPanel.getWidth(), this.graphPanel.getHeight());
BorderLayout panelMapLayout = new BorderLayout();
panel.setLayout(panelMapLayout);
panel.setVisible(true);
this.graphPanel.add(panel);
this.graphPanel.revalidate();
this.graphPanel.repaint();
// Paint on a new JFrame: perfectly working
JFrame frame = new JFrame("Simple Graph View 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
非常感谢这里的一些指导。
答案 0 :(得分:0)
我认为您忘记添加GUI面板。参见:
frame.getContentPane().add(vv);
应该是:
this.graphPanel.add(vv);
frame.getContentPane().add(this.graphPanel);
答案 1 :(得分:0)
删除BorderLayout,我不知道原因,但问题在于:
BorderLayout panelMapLayout = new BorderLayout();
panel.setLayout(panelMapLayout);