将MouseListener添加到

将MouseListener添加到

我对似乎是一个小问题感到震惊。我试图将MouseListener添加到Line2D对象,但无法正常工作。该方法或尝试过的方法无效还是我可以用另一种方法来做。帮我弄清楚我在做什么错。

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) {
          }

       });

        }
}

最佳答案

将MouseListener添加到LinesPanel。并使用MouseEvent坐标检查单击是否靠近直线。

How to select a line

10-04 13:13