سؤال

Just wondering what is the best practice way of creating a class that needs to handle mouse clicks and key presses. 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 have to have lots of empty methods in my class to satisfy the interfaces when I actually only need keyReleased and mouseReleased.

If I could use MouseAdapter and KeyAdapter I could get rid of these methods and have cleaner code. So any suggestions on a way to use these classes that isn't messier than what I already have.

هل كانت مفيدة؟

المحلول

Extend MouseAdapter and use Key Bindings in preference to KeyListener or KeyAdapter.

نصائح أخرى

You could inherit from one of the Adapter classes and then implement the other interface. That way you only need to do about half of the work.

I would suggest using the Adapter that provides the most method coverage, to minimize your work.

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

I'm going to go out on a limb and say that you shouldn't try to combine this functionality into one single class, that trying to do so is likely a bad design decision. If you say it's because they'll both be instigating the same actions, then by all means have both control classes share the same model, but otherwise create separate classes -- one to handle mouse interaction, and one to handle keyboard interaction (and as trashgod states, 1+ to him, -- using Key Bindings, not a KeyListener).

You can extend one, then use the "replace inheritance by delegation" refactoring (in Intellij, I assume eclipse has an equivalent) then extend the other

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top