Hello all,
I'm having problems adding a MouseListener to a canvas.
I have a class that extends Canvas, and I can't for the life of me add a
MouseListener. I've tried:
Adding a MouseListener from within the constructor:
this.addMouseListener(this);
As a side note: does this require me to override all the MouseEvent
methods? MouseClicked, MousePressed, etc.? Even if they are just
do-nothing methods. I do, anyway, because that is what I did with Event
listeners such as WindowEvent.
Also from the constructor with an Anon. Inner Class:
addMouseListener(new MouseListener(){
public void MouseClicked(MouseEvent e){
// Do stuff here
}
});
No extra overriding required here.
And now I've just tried adding it from main():
MousingAround le = new MousingAround();
le.addMouseListener(le);
Methods overriden.
Always I get:
"MousingAround.java:61: addMouseListener(java.awt.event.MouseListener)
in java.awt.Component cannot be applied to (MousingAround)"
But since the class MousingAround extends Canvas... it should work? The
book I'm following has a canvas created which has a MouseListener added
to it...?
The example does it a different way: the class extends Frame, and a
canvas is added to that Frame - but that shouldn't, as far as I know,
have any difference apart from *how* I add the MouseListener.
Massively cut-down, for your viewing pleasure source code follows:
Also, a note: a class called GUIFrame is referenced, I include the
source for this also. There are no problems with GUIFrame.
Any help appreciated. If I've done something boneheaded, please point
this out nicely, thanks!
===========CODE FOLLOWS==============
import java.awt.*;
import java.awt.event.*;
public class MousingAround extends Canvas{
Scrollbar horizontalBottomScrollBar;
Scrollbar verticalSideScrollBar;
public MousingAround(){
// Create the frame
Frame frame = new GUIFrame("MousingAround");
// Create and add other graphical thingymibobs
// Why did I include these even though they aren't
// part of the problem?
// Well, to show that I *can* use anonymous inner adapters!
BottomScrollBar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 20, 0, 50);
BottomScrollBar.addAdjustmentListener(new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent e){
repaint();
}
});
SideScrollBar = new Scrollbar(Scrollbar.VERTICAL, 0, 20, 0, 50);
SideScrollBar.addAdjustmentListener(new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent e){
repaint();
}
});
le.addMouseListener(le);
frame.add(BottomScrollBar, BorderLayout.SOUTH);
frame.add(SideScrollBar, BorderLayout.EAST);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setSize(420, 420);
frame.setResizable(true);
frame.setVisible(true);
}
// Override the MouseListener methods
public void MouseClicked(MouseEvent e){
System.out.println("Click!");
}
public void MouseEntered(MouseEvent e){}
public void MouseExited(MouseEvent e){}
public void MousePressed(MouseEvent e){}
public void MouseReleased(MouseEvent e){}
public static void main(String args[]){
// Create an instance of this class
MousingAround le = new MousingAround();
}
}
========= CODE ENDS ====================
=======HERE FOLLOWS THE CODE TO=========
========== GUIFrame.java ===============
import java.awt.*;
import java.awt.event.*;
public class GUIFrame extends Frame {
public GUIFrame(String title) {
super(title);
setBackground(SystemColor.control);
addWindowListener(new WindowAdapter() {
//only need to override the method needed
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
/* Centers the Frame when setVisible(true) is called */
public void setVisible(boolean visible) {
if (visible) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((d.width-getWidth())/2,(d.height - getHeight())/2);
}
super.setVisible(visible);
}
}
====== CODE ENDS HERE =============

Signature
Registered Linux User #364108. Get counted: http://counter.li.org
'"Impossible" isn't French, but French is impossible!'
Babu Kalakrishnan - 16 Sep 2004 12:14 GMT
> I'm having problems adding a MouseListener to a canvas.
>
[quoted text clipped - 7 lines]
> do-nothing methods. I do, anyway, because that is what I did with Event
> listeners such as WindowEvent.
All methods of the MouseListener interface start with a lower-case
alphabet. "mouseClicked" is not the same as "MouseClicked" in java.
Also when you call the addMouseListener method, the argument passed to
it must be declared as a "MouseListener". Since MouseListener is an
interface, you can attach it to any of your custom classes by adding
"implements MouseListener" to the class declaration, and implementing
*all* the required methods. Simply implementing the methods (even
properly spelt) does not make the class a MouseListener instance - it
needs to be explicitly declared as implementing the interface.
BK
Andrew Thompson - 16 Sep 2004 12:17 GMT
> I'm having problems adding a MouseListener to a canvas.
Try overriding isFocusable to return true,
if that fails, please post an SSCCE.
<http://www.physci.org/codes/sscce.jsp>
(No, the code you posted was *not* an SSCCE,
I wrestled with it for 10 minutes before I
gave up on it..)

Signature
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
Jacob - 16 Sep 2004 12:42 GMT
> Hello all,
> I'm having problems adding a MouseListener to a canvas.
[quoted text clipped - 8 lines]
> do-nothing methods. I do, anyway, because that is what I did with Event
> listeners such as WindowEvent.
Yes you need to implement them all. Extending MouseAdaptor is
an alternative as it implements tham all (empty) already and you
override the one(s) required. Often you can't use this approach
however as the class in question already extend some class.
You also need to explicitly "implement MouseListener" as Canvas
doesn't.
> Also from the constructor with an Anon. Inner Class:
> addMouseListener(new MouseListener(){
> public void MouseClicked(MouseEvent e){
> // Do stuff here
> }
> });
Try "mouseClicked" instead (lower-case "m") :-)
Will Gittoes - 17 Sep 2004 10:34 GMT
> > Hello all,
> > I'm having problems adding a MouseListener to a canvas.
[quoted text clipped - 13 lines]
> override the one(s) required. Often you can't use this approach
> however as the class in question already extend some class.
I try to avoid implementation for this reason, in case I am forced to do
it at some later point. So when you IMPLEMENT it, you over-ride just the
needed ones... and when you just have it as an inner anon. class you
must over-ride all of them?
That seems to have worked (over-ride, with a small m, everything
anonymously). Which is confusing, because adding a KeyListener I wasn't
forced to override all it's methods, just the one I wanted. Same with
the AdjustmentListener...?
> You also need to explicitly "implement MouseListener" as Canvas
> doesn't.
[quoted text clipped - 7 lines]
>
> Try "mouseClicked" instead (lower-case "m") :-)
Thanks :-)
Thanks to everyone else who replied, also!

Signature
Registered Linux User #364108. Get counted: http://counter.li.org
'"Impossible" isn't French, but French is impossible!'
Andrew Thompson - 17 Sep 2004 11:10 GMT
> That seems to have worked (over-ride, with a small m, everything
> anonymously). Which is confusing, because adding a KeyListener I wasn't
> forced to override all it's methods, just the one I wanted.
I think you are confused..
The KeyListener interface specifies the
methods a KeyListener must define, it declares
tham as 'abstract'.
The KeyAdapter *implements* the KeyListener
interface by providing (implementing) the
methods specified.
Since KeyAdapter defines a behaviour for all
KeyListener methods, you can simply override
the ones of interest to your application.

Signature
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
Babu Kalakrishnan - 17 Sep 2004 13:44 GMT
> Since KeyAdapter defines a behaviour for all
> KeyListener methods, you can simply override
> the ones of interest to your application.
I generally tend to avoid these "Adapters" altogether. It is easy to
mis-spell a method name (which the compiler will not compain about) and
you end up spending more time debugging the problem than it would have
taken you to write empty implementations for the unneeded methods in the
first place (Especially when IDEs like Eclipse will write the empty
wrappers for you anyway :-))
BK
Andrew Thompson - 17 Sep 2004 14:30 GMT
> I generally tend to avoid these "Adapters" altogether. It is easy to
> mis-spell a method name (which the compiler will not compain about) and
> you end up spending more time debugging the problem than it would have
> taken you to write empty implementations for the unneeded methods in the
> first place (Especially when IDEs like Eclipse will write the empty
> wrappers for you anyway :-))
I could not agree more, Babu. I never found
need for Adapters until I started making combined
applet/applications where the application Frame
(defined inside main()) benefitted from a WindowAdapter.
Folks who are learning Java, especially,
should avoid them completely.

Signature
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
Adam - 21 Sep 2004 13:35 GMT
>> Since KeyAdapter defines a behaviour for all
>> KeyListener methods, you can simply override the ones of interest
[quoted text clipped - 6 lines]
> methods in the first place (Especially when IDEs like Eclipse will
> write the empty wrappers for you anyway :-))
Well, if you are using Eclipse or alike, don't override manually, ask
the IDE
to produce the overriden method signature for you (Source->Override),
to be sure there are no spelling mistakes.
Adam
Will Gittoes - 17 Sep 2004 22:47 GMT
>>That seems to have worked (over-ride, with a small m, everything
>>anonymously). Which is confusing, because adding a KeyListener I wasn't
[quoted text clipped - 13 lines]
> KeyListener methods, you can simply override
> the ones of interest to your application.
Aaahhhhh, I see now.... So is there a MouseAdapter I can use? I've got
it working anyway.
Babu, posting below, has got a point about not getting a compiler error
- that was why I got confused. At least I know now; and a trip to USENET
has cemented it in my mind. I stand by adapters, though, implementing is
too klunky for me, I don't like it.

Signature
Registered Linux User #364108. Get counted: http://counter.li.org
'"Impossible" isn't French, but French is impossible!'
Thomas Fritsch - 16 Sep 2004 13:01 GMT
> Hello all,
> I'm having problems adding a MouseListener to a canvas.
[quoted text clipped - 6 lines]
> As a side note: does this require me to override all the MouseEvent
> methods? MouseClicked, MousePressed, etc.?
You have to override mouseClicked, mousePressed, etc. (with small *m*).
Method MouseClicked is *not* part of the MouseListener interface.
> Even if they are just
> do-nothing methods. I do, anyway, because that is what I did with Event
> listeners such as WindowEvent.
Take a look at class java.awt.event.MouseAdapter. This is probably what
you want.
> Also from the constructor with an Anon. Inner Class:
> addMouseListener(new MouseListener(){
> public void MouseClicked(MouseEvent e){
... mouseClicked ...
> // Do stuff here
> }
[quoted text clipped - 3 lines]
> And now I've just tried adding it from main():
> MousingAround le = new MousingAround();
Be sure to declare the MousingAround class with
"implements MouseListener"
> le.addMouseListener(le);
> ...
[quoted text clipped - 6 lines]
> Any help appreciated. If I've done something boneheaded, please point
> this out nicely, thanks!
You did a nice boneheaded bug ;-)

Signature
Thomas<dot>Fritsch<squiggle>ops<dot>de