You said your code just draws rectangles, then there will indeed be no way to select one with the mouse. Your code must keep track of what rectangle have been drawn and then check this list when a mouse click arrives. In the example there is a list of trees, each represented as an object. Each object has an associated hotsp i.e. a Shape (circle) at a particular coordinate location. One particular tree is the value of the global variable hottr. This tree is drawn in a different color.
Code:
public void paint(Graphics g) {
g.drawImage(diagram, 0, 0, this);
// draw all the items on the Tree list
for (Tree t : trees) {
gOff.setColor((t==hotTree) ? hotColor : treeColor);
gOff.fill(t.hotsp);
}
}
Code:
public void mouseMoved(MouseEvent e) {
TreeInfo oldHot = hottr;
hottr = null;
// if we are in range of one of 'trees', set hottr
for (Tree t : trees) {
if (t.hotSpot.contains(1.0 * e.getX(), 1.0 * e.getY())) {
hottr = tree;
break;
}
}
if (oldHot != hottr) repaint();
}
Bookmarks