简体   繁体   English

鼠标侦听器无法在Java中与JFrame一起使用

[英]Mouse Listener not working with a JFrame in Java

I'm trying to make a 2D game in Java. 我正在尝试用Java制作2D游戏。 I need a way to detect mouse input for player attacks and some other stuff. 我需要一种检测鼠标输入的方法,以防玩家攻击和其他一些东西。 I already have a working Key Listener in my game but when I tried adding a Mouse Listener the same way I did the Key Listener it doesn't work. 我的游戏中已经有一个工作正常的Key Listener,但是当我尝试以与我做Key Listener相同的方式添加Mouse Listener时,它就无法工作。

Here is my Mouse Listener class (Just some test codes for now and these line are never output in the console even when spamming my mouse everywhere on the display) 这是我的Mouse Listener类(目前只有一些测试代码,即使在显示屏上到处都是我的鼠标都发了垃圾邮件,这些行也不会在控制台中输出)

package input;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseInput extends MouseAdapter
{
public MouseInput()
{

}

@Override
public void mouseClicked(MouseEvent e)
{
    System.out.println("Hello");
}

@Override
public void mousePressed(MouseEvent e)
{
    System.out.println("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e)
{
    System.out.println("Mouse Released");
}
}

Also here is my display class where I create a JFrame and I add my canvas, Key Listener and Mouse Listener to it. 这也是我的显示类,在其中创建JFrame并向其添加画布,Key Listener和Mouse Listener。

package display;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;

import input.KeyInput;
import input.MouseInput;


public class Display
{
public static JFrame frame;
private Canvas canvas;

private String title;
private int width;
private int height;

private static double currtime = System.nanoTime();
private static double lasttime = 0;
private static double delta = 0;
private static float fps = 30;
private static int tick = 0;

public Display(String title, int width, int height)
{
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
}

private void createDisplay()
{
    frame = new JFrame(title);
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setFocusable(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width, height));
    canvas.setMinimumSize(new Dimension(width, height));
    canvas.setMaximumSize(new Dimension(width, height));
    canvas.setBackground(Color.WHITE); 

    frame.add(canvas); 
    frame.addKeyListener(new KeyInput()); // Add the keyListener
    frame.addMouseListener(new MouseInput()); // Add the mouseListener
    frame.pack();
    System.out.println(frame.getMouseListeners().length + " mouse listener found"); // This line outputs 1 mouse listener found
    System.out.println(frame.getKeyListeners().length + " key listener found"); // This line outputs 1 key listener found

}

public void update() // Called every frame
{
    frame.requestFocus();
    tick++;
    lasttime = currtime;
    currtime = System.nanoTime();
    delta = (currtime - lasttime) / 1000000000;
    fps = (float) (1 / delta);
    if (tick / getFPS() >= 2)
    {
        tick = 0;
        System.out.println("FPS = " + Math.round(getFPS()));
        try
        {
            System.out.println("Mouse Position = " + frame.getMousePosition().getX()
                    + ", " + frame.getMousePosition().getY());
        }
        catch (Exception e)
        {
            System.out.println("Mouse out of screen. Could not get mouse position (NullPointerException)");
        }
    }
}

public int getWidth()
{
    return width;
}

public int getHeight()
{
    return height;
}

public Canvas getCanvas()
{
    return canvas;
}

public JFrame getFrame()
{
    return frame;
}

public static float getFPS()
{
    return fps;
}
}

I looked through this forum for answer but every answer given did not fix it. 我通过这个论坛寻找答案,但是给出的每个答案都无法解决。

Tell me if you need any more information to help you solve the problem and thanks in advance for helping :D 告诉我您是否需要更多信息来帮助您解决问题,并感谢您:D

Add the MouseListener to the canvas object that covers the JFrame, and your code will work. 将MouseListener添加到覆盖JFrame的画布对象中,您的代码将起作用。 Note that as a side recommendation, you shouldn't be mixing AWT with Swing components. 请注意,作为附带建议,您不应将AWT与Swing组件混合使用。 Use a JPanel instead of a Canvas object. 使用JPanel而不是Canvas对象。

Later we may touch on why KeyListeners should usually be avoided, but since that's not the thrust of your question, we can shelve this for now. 稍后我们可能会谈到为什么通常应该避免使用KeyListeners的方法,但是由于这不是您提出问题的重点,因此我们现在可以搁置它。

eg, 例如,

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class Display2 extends JPanel {
    private int prefW;
    private int prefH;

    public Display2(int prefW, int prefH) {
        this.prefW = prefW;
        this.prefH = prefH;
        MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
        addMouseListener(myMouseAdapter);
        addMouseMotionListener(myMouseAdapter);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(prefW, prefH);
    }

    private static void createAndShowGui() {
        Display2 mainPanel = new Display2(500, 500);

        JFrame frame = new JFrame("Display");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

class MyMouseAdapter extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        System.out.printf("Mouse Pressed at: %s%n", e.getPoint());
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        System.out.printf("Mouse Released at: %s%n", e.getPoint());
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        System.out.printf("Mouse Dragged at: %s%n", e.getPoint());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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