I am at a total loss right now. I haven't worked much with building GUIs in Java, I've been reading all about swing and JPanel, and I think what I am trying to do is possible, I just haven't figured out how.
I'm trying to build a GUI in which you can draw straight lines within a certain drawing area, I would like to be able to get the start/endpoint coordinates in order to perform some math with those points. Any help would be greatly appreciated!
I will leave the code to you so here is the algorithm:
1. Create a
JFrame
and add aJPanel
to it.2. Add a mouse listener for the
JPanel
3. Every time the mouse is pressed, get the x and y of the click. (starting points)
4. When the mouse is dragged , record x and y continuously.
5. When mouse is released, record the x and y. (ending points)
6. You could either use the
drawLine()
method ofGraphics
class or usedraw()
ofGraphics2D
in this case you will need aLine2D.Double
-- the arguments remain the same - start x, start y, end x and end yhere is an image to explain a lil bit better:
you need to add the mouse listener on JPanel.
then:
To draw line with mouse move you can also add mouse motion listener.
This is harder than just "draw straight lines with (x1,y1) and (x2, y2)" approach.
You need a
Line
(your custom) object that is dynamically created and placed on theJPanel
which is listening forMouseEvent
s The canvas area being theJPanel
itself. You also need to separate the MODEL from the VIEW so that your custom canvasJPanel
will draw itself properly with an override forpaintComponent()
The question is slightly vague, so I can't provide any code.
Start with Performing Custom Painting and 2D Graphics.
Basically, you going to need a mouse listener to monitor the user interaction with your panel, check out How to write mouse listeners for more infor still.
Depending on your needs, if you need to maintain all the click points of the user, you would need to store them in something like a
List
, or if you just need to know the start and end points, the you just need a couple ofPoint
objects.You would be able to use these to paint onto your surface and performing your required calculations.
Remember, in this context, the points are contextual to the container they were generated on. That is 0x0 will be the top left of the container
Updated
You could also take advantage of the Shape API, using a
Line2D
to represent the two points. This would make it easier to distinguish between distinct lines/points