How to modify a graph appearance in JUNG

152 Views Asked by At

I'm trying to visualize a tree graph with the JUNG library.

The code I use is:

    JPanel base = new JPanel();

    Graph<String, String> grafo = OntologyGraph.getGraph(ontology);

    Layout<String, String> layout = new TreeLayout<String, String>((Forest<String, String>) grafo);
    VisualizationViewer<String, String> vv = new VisualizationViewer<String, String>(layout);

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);

    final DefaultModalGraphMouse<String, Number> graphMouse3 = new DefaultModalGraphMouse<>();
    vv.setGraphMouse(graphMouse3);
    graphMouse3.setMode(DefaultModalGraphMouse.Mode.PICKING);

    base.add(vv);

    return base;

It displays this
enter image description here

Now I want to change the circled verteces with a labelled JButton and to enlarge the space between them, but I can't find a tutorial on the web to achive this.

2

There are 2 best solutions below

1
Joshua O'Madadhain On

Changing the spacing between the nodes is easy enough; just use the TreeLayout constructor that accepts the distx and disty parameters.

Providing a JButton for each node is not something that JUNG natively supports, although you could do some hacking to enable it.

What problem are you trying to solve by using JButtons for nodes?

0
AudioBubble On

Here is some example code that you can use to open a JFrame with information about the node that was clicked (when you are in picking mode). If you want to have it respond to node clicks even when you are in the transforming mode, you'd have to change the graphmouseplugins a little to not remove the PickingGraphMousePlugin when in transforming mode.

    vv.getRenderContext().getPickedVertexState().addItemListener(new ItemListener(){
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                JFrame frame = new JFrame("Vertex "+e.getItem()+" picked");
                frame.getContentPane().add(new JButton("hello from "+e.getItem()));
                frame.setSize(new Dimension(200,100));
                frame.setLocation(200, 200);
                frame.setVisible(true);
            }
        }
    });

If you want the vertices to look more like rectangular buttons, the VertexLableAsShapeDemo may help. That demo uses JLabels to draw the vertices