0

I'm struck in a what it seems to be a minor problem. I tried to add MouseListener to Line2D object but it's not working. Is the method or tried is invalid or I can do it another way. Help me figure out what I'm doing wrong here.

public class DrawingLines {
    public static void main(String[] args){
        LineFrame lf = new LineFrame();
        lf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lf.setVisible(true);

    }   
}

class LineFrame extends JFrame{
    public LineFrame(){
        setTitle("Line test");
        setSize(500, 500);

       LinesPanel lp = new LinesPanel();
        Container contentpane = getContentPane();
        contentpane.add(lp);

    }
}

class LinesPanel extends JPanel{
    public LinesPanel(){

    }
    public void paintComponent(Graphics g){
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
       Line2D line = new Line2D.Double(105.5, 306.6, 350.8, 4.9);
       g2.draw(line);
       line.addMouseListener(new MouseListener(){
          @Override
          public void mouseClicked(MouseEvent e) {
              System.out.println("Line Clicked !");
          }

          @Override
          public void mousePressed(MouseEvent e) {
          }

          @Override
          public void mouseReleased(MouseEvent e) {
          }

          @Override
          public void mouseEntered(MouseEvent e) {
          }

          @Override
          public void mouseExited(MouseEvent e) {
          }

       });

        }
}
StanislavL
  • 56,971
  • 9
  • 68
  • 98

2 Answers2

1

Add the MouseListener to the LinesPanel. And use the MouseEvent coordinates to check whether the click is close to the line.

See How to select a line

StanislavL
  • 56,971
  • 9
  • 68
  • 98
0

The Line component doesn't have a clickable area so a mouselistener won't work properly, what you might want to do is add an invisible square/rectangle/polygon over it to handle the mouse instead.

Wep0n
  • 392
  • 3
  • 15