So I am having some trouble doing this. Basically I previously drew some line segments on a JPanel using Graphics2D and GeneralPath, and now I want to retrieve the Graphics2D/GeneralPath object when I click on it on the JPanel, is there anyway I can do this?
答案 0 :(得分:1)
I want to retrieve the Graphics2D/GeneralPath object when I click on it on the JPanel
You need to keep an ArrayList
of Shape
object that you draw. Then in the MouseListener you can get the mouse point and use the Shape.contains(...)
method to determine if the mouse click was on a Shape
you have drawn.
The Draw On Component
example from Custom Painting Approaches demonstrates the concept of painting an object from an ArrayList to get you started.
Edit:
The Shape.contains(...)
method doesn't work for lines.
Here is a quick attempt to write a contains(...) method for a Line2D object and a Point. Not sure how accurate it will be in real life.
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;
}
}