Hi
What is the best way to deal with Mouse Events on Canvas Items? I tried
make self contained objects with MouseListener drawn on the Canvas, but it
seems the MouseAdapter can't find them. I tried to have my objects
extending Component or JButton in hope the compiler would create the missing
link, but no. Since the number and location of items change each time, I
find it tedious (not mentioning stupid in an Object-Oriented environment) to
have the Canvas track all items.
Thanks,
Thierry
sanjay manohar - 07 Apr 2005 17:14 GMT
To have objects that respond to mouse events in the way you describe,
using a MouseListener:
1) They must be Components, as you correctly inferred, and therefore
ONLY A RECTANGULAR area will be clickable.
2) They must be added to the parent component. (This is so that java
knows the bounds of the component, and is able to automatically find
out which component has been clicked on).
3) You must register the mouse listener to each one. E.g. you could do
this in the constructor
4) Sounds like you are drawing on a Canvas, but in fact you should
paint each component on its own Graphics object (from the paint
method). If there is nothing else drawn on the canvas except for your
rectangular canvas items, then use a JPanel?
5) Note that you need to use different coordinate systems if your
components are extending Component.
e.g.
/*******************************/
JPanel container = new JPanel();
// This means I will specify the positions of
// each component explicitly
container.setLayout(null);
CanvasItem item1=new CanvasItem();
container.add(item);
// this controls both the location the item is painted,
// and the area that responds to mouse events.
item.setBounds(x,y,w,h);
class CanvasItem extends JComponent {
public CanvasItem(){
addMouseListener(myMouseListener);
}
protected MouseListener myMouseListener = new MouseAdapter(){
//add listener methods here
};
public void paint(Graphics g){
//draw this item on its own graphics
}
}