鼠标侦听器不使用Java中的JFrame

时间:2015-08-16 20:19:39

标签: java swing

我正在尝试用Java制作2D游戏。我需要一种方法来检测玩家攻击和其他东西的鼠标输入。我已经在我的游戏中有一个工作的Key Listener,但是当我尝试添加一个Mouse Listener时,就像我使用Key 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");
}
}

此处是我的显示类,我在其中创建了一个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;
}
}

我查看了这个论坛的答案,但是给出的每个答案都没有解决它。

告诉我您是否需要更多信息来帮助您解决问题,并提前感谢您的帮助:D

1 个答案:

答案 0 :(得分:5)

将MouseListener添加到覆盖JFrame的canvas对象,您的代码将起作用。请注意,作为辅助建议,您不应将AWT与Swing组件混合使用。使用JPanel而不是Canvas对象。

稍后我们可能会谈到为什么通常应该避免KeyListeners,但由于这不是你问题的主旨,我们现在可以搁置它。

如,

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());
    }
}