hi guys, I wonder if anybody can clarify something for me.
Take these 2 fragments of code (2 constructors belonging to 2 different applications):
First one:

public MouseTrackerFrame()
   {
      super( "Demonstrating Mouse Events" );

      mousePanel = new JPanel(); // create panel
      mousePanel.setBackground( Color.WHITE ); // set background color
      add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame

      statusBar = new JLabel( "Mouse outside JPanel" ); 
      add( statusBar, BorderLayout.SOUTH ); // add label to JFrame

      // create and register listener for mouse and mouse motion events
      MouseHandler handler = new MouseHandler(); 
      mousePanel.addMouseListener( handler ); 
      mousePanel.addMouseMotionListener( handler ); 
   } // end MouseTrackerFrame constructor
   private class MouseHandler implements MouseListener, 
  MouseMotionListener 
  ...

Second one:

public MouseDetailsFrame()
   {
      super( "Mouse Clicks and Buttons" );

      statusBar = new JLabel( "Click the mouse" );
      add( statusBar, BorderLayout.SOUTH );
      addMouseListener( new MouseClickHandler() ); // add handler
   } // end MouseDetailsFrame constructor
      private class MouseClickHandler extends MouseAdapter{ 

...

Now, the first one is registering the handlers like so:

MouseHandler handler = new MouseHandler(); 
          mousePanel.addMouseListener( handler ); 
          mousePanel.addMouseMotionListener( handler ); 

with an object of type JPanel (mousePanel) that calls addMouseListener method.
In the second example the handler is registered only with addMouseListener( new MouseClickHandler() ); // add handler...so what is addMouseListener method applied to if there is no object that is used to call the method?!
I hope what I mean is clear,

  • how easilly could be to trace code from an SSCCE, short, runnable, compilable not from description

  • nobody knows if is there used MouseListener and MouseMotionListener or restricted in MouseAdapter

_____________________________________________________________

  • (repeating) every Listeners (excluding DocumentListener) can returns an Object, you can to compare (==) this Object with desired JComponent (best of ways is if this component is initialized and to be stored in Local Variable)

The second code is valid only if its in a class that extends a swing component that accepts mouse listeners, eg extends JPanel. Because there is no explicit obect for the the call, it's the same as this.addMouseListener which is OK if this is an instance of a class that inherits addMouselistener

ah I see, so they are essentially the same thing, and yes the second one extends a JPanel

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.