Search code examples
javajung

How to configure a VisualizationViewer so users can move nodes with the mouse?


I'm using Jung 2.0 for a while now, but I'm a bit confused with all the configuration code that is done in the various demos that ship with the package.

Could anyone tell me how to configure a VisualizationViewer so that I can move the graph nodes around by clicking and draging them with the mouse?

The code I have is below. It's a mix of the various demos I studied. But I can only pan and rotate the graph with it.

public class GrafoParticipacaoSocietaria extends JFrame {

    Graph<VerticeParticipacaoSocietaria, Integer> graph;
    VisualizationViewer<String, String> vv;
    Layout<VerticeParticipacaoSocietaria, Integer> layout;

    public GrafoParticipacaoSocietaria(Graph<VerticeParticipacaoSocietaria, Integer> grafoPart) {
        super("Participação Societária");

        graph = grafoPart;
        layout = new ISOMLayout(graph);

        final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout);
        vv = new VisualizationViewer(visualizationModel);

        vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
        vv.setForeground(Color.blue);
        getContentPane().add(vv);

        // this class will provide both label drawing and vertex shapes
        VertexLabelAsShapeRenderer<String, String> vlasr = new VertexLabelAsShapeRenderer<String, String>(
                vv.getRenderContext());

        vv.getRenderContext().setVertexShapeTransformer(vlasr);
        vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.lightGray));
        vv.getRenderContext().setEdgeDrawPaintTransformer(new ConstantTransformer(Color.lightGray));
        vv.getRenderContext().setEdgeStrokeTransformer(new ConstantTransformer(new BasicStroke(1.0f)));

        // customize the renderer
        // vv.getRenderer().setVertexRenderer(new MyGradientVertexRenderer<String, String>(Color.cyan, Color.white, true));
        vv.getRenderer().setVertexLabelRenderer(vlasr);

        vv.setGraphMouse(new DefaultModalGraphMouse());
    }
}

Solution

  • You can find an example on the Jung website here use Editing to add nodes and then switch to Picking to move the nodes you have added. The sourcode is avalaible from SourceFource check out jung-samples-X.X.X.jar the class called GraphEditorDemo

    enter image description here Screen shot from the Jung Website