I have a mouseListener which i want to attatch to more than one object. And i want a differant response depending on what object i click on.
I am aware that i could just write a new listener for each of the objects but that would be very bad practice.
How can i get java to tell me what object i have clicked on?
class MousePressListener implements MouseListener
{
public void mouseClicked(MouseEvent event)
{
System.out.println(" detected on "
+ event.getSource().getClass().getName());
scrollRight(); }
public void mousePressed(MouseEvent event){}
public void mouseMoved(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
This will tell me Javax.Swing.JLabel
for example, but it wont distinguish between th differant JLabels/JButtons i am clicking on. How can i return the path or text associated with the object??
02-09-2005, 09:53 AM
lionelBadiou
Hello,
public void mouseClicked(MouseEvent event)
{
if (event.getSource() == myButton1)
{
...
}
else
if (event.getSource() == myButton2)
{
...
}
}
Best regards,
02-09-2005, 01:44 PM
tommot82
i sorted it last night, but thankyou very much.
(I ended up doing it exactly the way you suggested)
Thanks again
02-14-2005, 05:18 AM
sjalle
Just as a note: for buttons you can also check the value
returned from the getText() method, giving you the label
string.