简体   繁体   中英

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?

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).

在此处输入图片说明

Attach it to the Canvas

You should add the mouse listener to the canvas, there is one reason for it: Coordinates.

If you attach mouse listener to the frame the 0-point of coordinates will be on the left-up corner of JFrame border . It will be hard to calculate the coordinates relative to canvas.

Instead of you can attach mouse listener to Canvas . The coordinates will be better with this. But do not forget to gain focus on canvas after adding listener:

canvas.addMouseMotionListener(motionListener);
canvas.requestFocus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM