2015-05-14 36 views
0

正如标题所说,我希望能够右键单击我在Jpanel上绘制的线条。由于这些行不是组件,我不能简单地将MouseListener添加到它们。目前,我吸取了我的JPanel线,下面的代码:如何将鼠标监听器添加到用Graphics.drawLine绘制的线条()

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D) g; 
    for (UserDrawnLine line : userDrawnLines) { 
     g.setColor(new Color(line.colorRValue,line.colorGValue, line.colorBValue)); 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.setStroke(new BasicStroke(line.thickness)); 
     g.drawLine(line.startPointX, line.startPointY, line.endPointX, line.endPointY); 
    } 
} 

这是我UserDrawnLine类:

public class UserDrawnLine { 
    public int startPointX; 
    public int startPointY; 
    public int endPointX; 
    public int endPointY; 
    public int colorRValue; 
    public int colorGValue; 
    public int colorBValue; 
    public float thickness; 



    public UserDrawnLine(int startPointX, int startPointY, int endPointX, int endPointY, int colorRValue,int colorGValue,int colorBValue, float thickness) { 
     this.startPointX = startPointX; 
     this.startPointY = startPointY; 
     this.endPointX = endPointX; 
     this.endPointY = endPointY; 
     this.colorRValue=colorRValue; 
     this.colorBValue=colorBValue; 
     this.colorGValue=colorGValue; 
     this.thickness=thickness; 
    } 
} 

我一直在考虑存储通过行云点,然后反应因此当用户在其中一个点上点击Jpanel时。但是,这似乎并不是最好的解决方案。有更好的吗?

回答

1

创建一个收线,并使用从MouseEventMouseListener提供的Point,遍历集合并检查点上的每个Line。您可能需要滚动您自己的Line类并实施contains方法(请注意,Line2D不能使用,因为它的包含方法始终返回false)。

要确定一个点P是就行:

距离P)+ 距离P)= 距离A,B

其中AB是行终点,而P是测试点。可以使用一个误差项来允许接近但不完全在线上的点(例如,当使用更宽的笔划来渲染时,您可能希望增加此误差项)。假设你的类具有端点一个b

public boolean contains(Point p, double error){ 
    double dist = Math.sqrt(Math.pow(p.x - a.x, 2) + Math.pow(p.y - a.y, 2)) + 
      Math.sqrt(Math.pow(p.x - b.x, 2) + Math.pow(p.y - b.y, 2)); 
    return Math.abs(dist - this.distance) <= error; 
} 
+1

['Line2D.contains'](http://docs.oracle.com/javase/8/docs/api/java/awt/geom /Line2D.html#contains-java.awt.geom.Point2D-)总是返回false,因此它绝对不能用于此目的。 – Radiodef

+0

@Radiodef,感谢您的澄清。该选项已被删除。 – copeg

+0

@copeg非常感谢,你的解决方案就像一个魅力:) – Endrew