• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Drawing a line between two points with a preview

 
Jan Hoppmann
Ranch Hand
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I have a problem that I don't know how to solve.

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,

Jan
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jan Hoppmann
Ranch Hand
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic