Doubt in Listener interface working mechanism

Discussion in 'Java' started by shyam_oec, Feb 23, 2008.

  1. shyam_oec

    shyam_oec New Member

    Joined:
    Nov 26, 2007
    Messages:
    89
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Developer, .NET Framework
    Location:
    Jamshedpur
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    
    /*
    <applet code="AdapterDemo" width=300 height=100>
    </applet>
    */
    
    public class AdapterDemo extends Applet
    {
      String str="";
    
      public void init()
      {  setBackground(Color.red); 
         addMouseListener(new MyMouseAdapter());
         addMouseMotionListener(new MyMouseMotionListener());
      }
         
       public void paint(Graphics g)
       {
         g.drawString(str,20,30);
       }
    
    }
    
    class MyMouseAdapter extends MouseAdapter
    {
      AdapterDemo adapterdemo=new AdapterDemo();
      public void mouseClicked(MouseEvent me)
     { adapterdemo.showStatus("mouse clicked");   
        adapterdemo.str="mouse clicked";
        adapterdemo.repaint();
     }
    }
    
    class MyMouseMotionListener extends MouseMotionAdapter
    {
       AdapterDemo adapterdemo=new AdapterDemo(); 
      public void mouseMoved(MouseEvent me)
      {
        int x,y;
        x=me.getX();
        y=me.getY();
        adapterdemo.str="mouse moved";
        adapterdemo.repaint(); 
        adapterdemo.showStatus("mouse at :"+x+","+y);
      }
    }

    Why this code generated runtime error/exceptions.Is it always necessery to pass event generator object reference to the Event Listener class through 'this',as a parameter in the event registration method?
    like addMouseListener(new MyMouseAdapter(this));
    addMouseMotionListener(new MyMouseMotionListener(this));
     
    Last edited by a moderator: Feb 24, 2008

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice