Harper
Harper

Reputation: 140

How to implement a mouseListener

I know that at the beginning of a class you can write implements ActionListener and then you must create public void actionPerformed(ActionEvent e) for it to be workable. Is it possible to do the same thing with the mouseListener? if so, what method do you have to create in place of actionPerformed?

Edit: this is my class declaration:

public class Basic_Book extends JFrame implements ActionListener implements MouseListener

And this is my error message that shows up next to it:

Upvotes: 1

Views: 11076

Answers (4)

Lews Therin
Lews Therin

Reputation: 10995

If you look at the javadocs.. there are a bunch of methods that come with MouseListener. In other not to implement everything, you can use a MouseAdapter which implements MouseListener and other interfaces, but already providing stub methods.

mouseClicked, mouseEntered etc.. Following your edit:

class Basic_Book extends JFrame implements ActionListener,MouseListener

Use a comma to separate the interfaces. ActionListener only has actionPerformed so you have to implement only that for ActionListener, MouseListener has 4 or more, you need to implement ALL. Or use MouseAdapter and override the necessary methods.

For the serialVersionUID, let Eclipse do that for you. Try ctrl+space on the error to invoke Eclipse's intellisense, it will give you some options. Choose the one that says generate serialVersionUID,

I can't remember how it is actually done (but it should work! Fingers crossed).

Upvotes: 6

MadProgrammer
MadProgrammer

Reputation: 347314

Like ActionListener and MouseListener is an interface, which means, yes, you can implement in the same way.

MouseListener defines five methods which you must implement.

  • mouseClicked(MouseEvent e)
  • mouseEntered(MouseEvent e)
  • mouseExited(MouseEvent e)
  • mousePressed(MouseEvent e)
  • mouseReleased(MouseEvent e)

You really should check with the Java Docs and tutorials first

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83557

The Official Java API Documentation is an essential tool for any Java programmer. In particular, check out the docs for MouseListener to see what methods you need to implement.

You can also simply add implements MouseListener and try to compile your class. The compiler will quickly tell you what methods you need to implement. If you are using an IDE such as Eclipse, NetBeans, or IntelliJ, you don't even need to compile your code. Each IDE has its own way of telling you what methods you need and even generate bodies of the methods for you. I strongly suggest that you familiarize yourself with a good IDE. It will save you a lot of time writing code.

Upvotes: 2

Selim
Selim

Reputation: 1132

Actually the compiler should tell you the answer but should be something like mouseLeave, mouseEnter, mouseHover, mousePressed

Upvotes: 0

Related Questions