Search code examples
javacanvasjframemouselistenermousemotionlistener

Do I add MouseListeners to the Canvas or to JFrame


I was trying to add a mouseListener and a mouseMotionListener to my game and noticed that I can add them to the Canvas or to the JFrame. Do I add it to both or one of them?


Solution

  • What I recommend is using the Canvas. When you are using a listener of any kind, think of where the actions will occur. Do all of your updates happen on the frame or on the canvas? If it is the latter, use the canvas to handle all of your action listener objects.

    Another way to think of it is that the JFrame is just a window holding the implementation of your game. Your graphic updates, keyboard inputs, mouse inputs, and any other functionality is done through the canvas.

    For example, compare the JFrame and canvas to this image of Skyrim. The window on the outside (A JFrame Object) has a close/minimize feature and the window holds the game screen (A Canvas Object).

    enter image description here