Here's what I'd like to do:
I have a JFrame with a grid of squares, and if I click on one of these squares, I want to take this one as starting point, and while I move the mouse to the other squares I want to see a line between this square and the starting point, so that I have a preview, and I want to fix this line by clicking on a second square. The preview part is kinda hard, I know how to draw a line when the user moves his mouse, but I don't know how to delete it if he moves the cursor into another square.
Thanks in advance,
Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses.
Here's how I've done it in the past:
- create a class for the lines, with a start point and end point (you can add other properties like color, thickness, etc)
- keep a collection with all lines
- keep a reference to the currently drawn line (e.g. currentLine)
- upon clicking the first time, create the currently drawn line (currentLine = new Line(startPoint, currentPoint);) -- the start point could be the center of the block, or the current point as well
- upon clicking the second time set the end point of the current line, add the line to the collection, and clear the current line (currentLine = null)
- in your mouse moved event check if the current line is set (currentLine != null); if so update the end point and repaint the panel
- in the painting, draw all lines from the collection, then draw the current line if it's set
You may even want to move the drawing of the lines to your line class; this also allows you to override the class to add extra drawing features without having to change the panel's repainting.
Ah, it works, thanks!
The only problems I have left are a flickering of lines (I think with double buffering and full screen mode, this shouldn't be an issue) and a strange offset in coordinates, but there must be a problem in my calculations... So this is resolved
Thanks so much!