Search code examples
vertexjung

JUNG Simulation


I'm doing a project in JUNG. I want to add a mouse event which will be called when the user will move a node or vertex. I have tried multiple listeners like, ItemListener, GraphMouseListener..

I have tried this, n some similar codes:

          vv.addGraphMouseListener(new GraphMouseListener() {

            @Override
            public void graphClicked(Object v, MouseEvent me) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void graphPressed(Object v, MouseEvent me) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void graphReleased(Object v, MouseEvent me) {

           Object subject = me.getSource();
                // The graph uses Integers for vertices.
                if (subject instanceof VertexFactory) {
                    VertexFactory vertex = (VertexFactory) subject;
                    if (pickedState.isPicked(vertex)) {
//                        selectedNode = vertex;
                        System.out.println("Vertex " + vertex
                                + " is now selected");
                        re.calDistance(bs.get(0));
                        dest();
                        vv.repaint();
                        vv.updateUI();

                    }
                }
            }
       });

Solution

  • I would suggest extending the PickingGraphMousePlugin and adding it to your GraphMouse

    http://jung.sourceforge.net/doc/api/edu/uci/ics/jung/visualization/control/PickingGraphMousePlugin.html

    public class MovingGraphMousePlugin<V, E> extends PickingGraphMousePlugin<V, E> {
    
        @Override
        public void mousePressed(MouseEvent e) {
            super.mousePressed(e);
            if(vertex != null) {
                System.out.println(vertex + " was picked.");
            }
        }
    }
    

    and then for example:

    DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    graphMouse.add(new MovingGraphMousePlugin<V, E>());
    visualViewer.setGraphMouse(graphMouse);
    

    This is just a rough example and will only tell you that a vertex has been picked. If you want to print if a vertex has been moved, you would have to override the mouseReleased method, too. You then would have to compare the two points where the mouse has been pressed and where it has been released (e.getPoint()).