Reputation: 15
I need to draw a line in JPanel with mouse, clicking two points in panel. First click would be the start of the line, and second click would be the end of the line.
I have something like this:
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Graphics g = this.jPanel1.getGraphics();
int x = evt.getX();
int y = evt.getY();
g.drawLine(x, y, x, y);
}
But it only draws pixel. Line with coordinates I need something like this, but just drawing it with mouse clicking.
Upvotes: 0
Views: 4080
Reputation: 8202
You're drawing a line from (x, y) to (x, y) which is why you're getting just a single pixel. You need to capture the co-ordinates of the first click, and then draw the line on the second click.
private int startX = -1;
private int startY = -1;
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
if (startX == -1 && startY == -1) {
startX = evt.getX();
startY = evt.getY();
} else {
Graphics g = this.jPanel1.getGraphics();
g.drawLine(startX, startY,
evt.getX(), evt.getY());
// reset the start point
startX = -1;
startY = -1;
}
}
Upvotes: 1
Reputation: 4899
From the doc
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
In your case x1=x2 and y1=y2, that's why your line is 1 pixel long. After each click you must record the coordinates of your click so that you can use them as the origin of the line for the next click.
Upvotes: 1