I have a composite tree. I've drawn this tree to a JPanel
width Graphics
object via overriding paintComponent(Graphics gr)
. My problem is: how can I access which component is clicked?
I only figured out trivial and bad solutions, so that's why I turn to you. Thanks in advance!
The shapes you have drawn, you need to store. When you receive a Mouse clicked event:
public void mouseClicked(MouseEvent e) {
you will have x and y from
e.getPoint().getX()
e.getPoint().getY()
You can then traverse your shapes, and see if a Shape contains the point above. From the Javadoc of Shape:
/**
* Tests if the specified coordinates are inside the boundary of the
* <code>Shape</code>, as described by the
* <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
* definition of insideness</a>.
* @param x the specified X coordinate to be tested
* @param y the specified Y coordinate to be tested
* @return <code>true</code> if the specified coordinates are inside
* the <code>Shape</code> boundary; <code>false</code>
* otherwise.
* @since 1.2
*/
public boolean contains(double x, double y);