DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2004
    Posts
    15

    MouseListener problem

    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??

  2. #2
    Join Date
    Jan 2005
    Posts
    45
    Hello,

    public void mouseClicked(MouseEvent event)
    {
    if (event.getSource() == myButton1)
    {
    ...
    }
    else
    if (event.getSource() == myButton2)
    {
    ...
    }
    }

    Best regards,
    Lionel Badiou
    CodeFutures -
    Java Code Generation

    http://www.codefutures.com



  3. #3
    Join Date
    Oct 2004
    Posts
    15
    i sorted it last night, but thankyou very much.

    (I ended up doing it exactly the way you suggested)

    Thanks again

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Just as a note: for buttons you can also check the value
    returned from the getText() method, giving you the label
    string.
    eschew obfuscation

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links