1

I'm trying to write an application in java that connects two jLabels on a panel by dragging a line from one to the other. I can create lines between two points on the panel OK but I can't figure out how to get the panel to recognise that when I hold the mouse down on the label I want to start drawing the line, and likewise that when I release the mouse on the target I want to stop drawing.

I draw the lines by overriding the panel's paintComponent method:

@Override
public void paintComponent(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    Enumeration e = stack.elements();

    g2d.setPaint(Color.black);

    while (e.hasMoreElements()) {
        g2d.draw((Line2D) e.nextElement());
    }

    g2d.setPaint(blank);
    g2d.draw(savedLine2d);

    g2d.setPaint(Color.black);
    g2d.draw(line2d);

}

1 Answers1

0

To detect dragging that stars on a JLabel, register a motion listener on that label:

    JLabel lable = new JLabel("Drag test");
    //add motion listener to label
    lable.addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseMoved(MouseEvent e) {
            // do nothing

        }

        @Override
        public void mouseDragged(MouseEvent e) {
            System.out.println("Dragging " + e.getX()+"-" + e.getY());
        }
    });
c0der
  • 18,467
  • 6
  • 33
  • 65
  • Thanks for the reply. I still can't get it to work. Do I have to pass the MouseDrag events out to the containing panel or something like that? – nimbinensis Mar 25 '17 at 10:19