【发布时间】:2016-07-11 20:36:01
【问题描述】:
所以我在执行此操作时遇到了一些麻烦。基本上我之前在 JPanel 上使用 Graphics2D 和 GeneralPath 绘制了一些线段,现在我想在 JPanel 上单击它时检索 Graphics2D/GeneralPath 对象,有什么办法可以做到吗?
【问题讨论】:
所以我在执行此操作时遇到了一些麻烦。基本上我之前在 JPanel 上使用 Graphics2D 和 GeneralPath 绘制了一些线段,现在我想在 JPanel 上单击它时检索 Graphics2D/GeneralPath 对象,有什么办法可以做到吗?
【问题讨论】:
当我在 JPanel 上单击 Graphics2D/GeneralPath 对象时,我想检索它
您需要保留您绘制的Shape 对象中的ArrayList。然后在 MouseListener 中你可以获取鼠标点并使用Shape.contains(...) 方法来确定鼠标点击是否在你绘制的Shape 上。
Custom Painting Approaches 中的 Draw On Component 示例演示了从 ArrayList 绘制对象的概念以帮助您入门。
编辑:
Shape.contains(...) 方法不适用于行。
这里是为 Line2D 对象和 Point 编写 contains(...) 方法的快速尝试。不确定它在现实生活中的准确度。
import java.awt.*;
import java.awt.geom.*;
class LineContains
{
public static void main(String...args)
{
Point point = new Point(10, 19);
Line2D.Double line = new Line2D.Double(0, 0, 10, 20);
boolean result = LineContains.contains(line, point);
System.out.println( result );
}
static boolean contains(Line2D line, Point point)
{
double[] location = new double[6];
PathIterator pi = line.getPathIterator(null);
pi.currentSegment(location);
int x1 = (int)location[0];
int y1 = (int)location[1];
pi.next();
pi.currentSegment(location);
int x2 = (int)location[0];
int y2 = (int)location[1];
double xDelta = x2 - x1;
double yDelta = y2 - y1;
double iterations = Math.max(Math.abs(xDelta), Math.abs(yDelta));
double xMultiplier = xDelta / iterations;
double yMultiplier = yDelta / iterations;
for (int i = 0; i < iterations; i ++)
{
int x = (int)Math.round( x1 + (i * xMultiplier) );
int y = (int)Math.round( y1 + (i * yMultiplier) );
//System.out.println(x + " : " + y);
if (x == point.x
&& y == point.y)
return true;
}
return false;
}
}
【讨论】:
Shape.contains(...) 不能在线工作。见编辑。