如何在JFrame中的其他内容下添加mouselistener?

时间:2017-04-02 05:47:18

标签: java jframe jpanel mouselistener

如果我的问题听起来很愚蠢,我很抱歉,我还是java新手。我要告诉你这段代码:

public class Window extends JFrame{


    private static final long serialVersionUID = -2139430787087799923L;

    private TransparentJPanel mousepanel;

    public Window(int width, int height, String title, Game game) {
        super(title);   
        HandlerClass handler = new HandlerClass();
        mousepanel = new TransparentJPanel();
        mousepanel.addMouseListener(handler);

        setPreferredSize(new Dimension(width,height));
        setMaximumSize(new Dimension(width,height));
        setMinimumSize(new Dimension(width,height));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
        add(game);      <-- here I add the game
        add(mousepanel);    <-- here I add the panel with the mouselistener
        game.start();
    }
}

TransparentJPanel类:

private class TransparentJPanel extends JPanel {
    private static final long serialVersionUID = 8855609189172945035L;

    TransparentJPanel() {
        super() ;
        this.setOpaque( false ) ;
        this.setLayout( null ) ;
    }
}

当我首先添加游戏时,游戏出现并且鼠标监听器不起作用,但是当我首先添加jpanel时,游戏不会显示,但是mouselistener可以工作。 这是我的HandlerClass类:

private class HandlerClass implements MouseListener {
    public void mouseClicked(MouseEvent event) {
        System.out.println(String.format("Clicked at %d,%d", event.getX(), event.getY()));
    }

    public void mouseEntered(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Entered frame at X: " + x + " - Y: " + y);

    }
    public void mouseExited(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Exited frame at X: " + x + " - Y: " + y);

    }
    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Pressed frame at X: " + x + " - Y: " + y);

    }

    public void mouseReleased(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Released at X: " + x + " - Y: " + y);

    }

}

所以,这是我的问题。 请帮忙。

1 个答案:

答案 0 :(得分:0)

解决方案结果很简单!

不是为鼠标侦听器创建面板,而是可以向游戏对象添加一个mouselistener,如下所示

public Window(int width, int title, String title, Game game) {
    super(title);
    HandlerClass handler = new HandlerClass();

    setPreferredSize(new Dimension(width,height));
    setMaximumSize(new Dimension(width,height));
    setMinimumSize(new Dimension(width,height));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);

    setVisible(true);
    add(game, BorderLayout.CENTER);
    game.addMouseListener(handler);     
    game.start();
}

希望这有帮助!