Both MouseAdapter and KeyAdapter must be "extended"

Just wondering what is the best way to create a class that should handle mouse clicks and keystrokes. Obviously it is not possible to inherit multiple classes in Java, so at the moment I am using the MouseListener and KeyListener interfaces, which means I must have many empty methods in my class to satisfy the interfaces when I really only need keyReleased and mouseReleased.

If I could use MouseAdapter and KeyAdapter, I could get rid of those methods and have cleaner code. So any suggestions for using these classes that are not dirtier than what I already have.


source to share

4 answers

Extend MouseAdapter

and use key bindings instead of KeyListener

or KeyAdapter




You can inherit from one of the classes Adapter

and then implement another interface. Thus, you only need to do about half of the work.

I would suggest using the Adapter

one that provides the most coverage of the method in order to minimize your work.

If you are already inheriting something else, then you obviously have no choice but to implement the two interfaces.



I'm going to go to a limb and say that you shouldn't try to bundle this functionality into one class, that trying to do this is probably a bad design decision. If you say this because they will both push the same actions, then anyway both control classes have the same model, but otherwise create separate classes - one to handle mouse interaction and the other - to interact with the keyboard (and like trashgod, 1+ to it - using key bindings, not a KeyListener).



You can extend it and then use the "replace inheritance with delegation" refactoring (in Intellij, I assume eclipse has an equivalent), then extend the rest



All Articles