Java2D: capturing event in Line object

I have a JPanel that has a string, circle, etc. Now when I click on the row the event will be reported as a line event or a generic JFrame event. I need to be able to move the line if the user clicks on the line and moves it. Is this possible in Java2D?

+2


a source to share


4 answers


Yes, but you will need to do some work (see java.awt.Shape). Basically you need to keep track of a list of shapes. The JPanel will receive a mouse event, which you can translate to coordinates (x, y). Then you can call Shape.contains (x, y) to see if your various shapes have been clicked.



This will work well for Circle, Polygon, Arc, etc .; however, in the case of Line2D, this will not work so easily, but you can use Line2D.intersects () with a small rectangle around the mouse click (this is also a good interface, since you don't want to force the user to click exactly on a pixel that is difficult to see).

+4


a source


There is no such thing as a "line event" unless you decide to implement it.



I would suggest adding MouseListener

and MouseMotionListener

to Canvas

or JPanel

on which your geometric shapes are drawn. Use a callback MouseListener

mousePressed(MouseEvent)

to determine if a given form was clicked. Once you have this set, use the method MouseMotionListener

mouseDragged(MouseEvent)

to move and redraw the shape as you move the mouse cursor.

+2


a source


+1


a source


I created a canvas markup library in Java a few years ago, and if you don't have to worry about transformations on the canvas (scaling, rotating, etc.), it's very easy to do.

Basically, you just need to maintain a collection of canvas shapes in a list (and not in a set, because the order of Z is probably important). The mouse listener will be on your canvas, not on individual shapes. Add new items to the beginning of your collection (or move the list back later).

When the canvas receives a mouse down event, loop through your collection of shapes until you find the one below your mouse coordinates. The easiest way to do this is for your shapes to implement an interface that some kind of hitPoint (int x, int y) method defines. So your rectangles can implement contains (), lines can do intersects () or graphic paths, you can account for some bumps, etc.

Taking it one step further, your shapes should define their own draw method (Graphics2D g) so you can easily do things like select boxes, or set the drawing mode to XOR to make it easier to "move" the shape. The paintComponent method of your canvas will simply have to loop through your collection of shapes, calling shape.draw (g) on ​​each one, passing in the graphics instance provided to the paintComponent method.

0


a source







All Articles