【问题标题】:JButton MouseListener not respondingJButton MouseListener 没有响应
【发布时间】:2013-01-07 02:10:17
【问题描述】:

我正在尝试构建一款扫雷类型的游戏,更具体地说,是曾经出现在 MSN 游戏中的两人游戏。我有一个 Tile 对象的多维数组。每个 Tile 都有一个状态(地雷、空白或相邻的地雷数量)。我有一个 GUI 类来处理程序的所有前端方面。

每个 Tile 都扩展了 JButton 并实现了 MouseListener,但是当我单击一个按钮时,它不会触发相应按钮/tile 的 MouseClicked 方法。

代码如下:

public class Tile extends JButton implements MouseListener {

private int type;

public Tile(int type, int xCoord, int yCoord) {
    this.type = type;
    this.xCoord = xCoord;
    this.yCoord = yCoord;
}

public int getType() {
    return type;
}

public void setType(int type) {
    this.type = type;
}

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

}

还有 GUI 类:

public class GUI extends JPanel {

JFrame frame = new JFrame("Mines");
private GameBoard board;
private int width, height;

public GUI(GameBoard board, int width, int height) {
    this.board = board;
    this.width = width;
    this.height = height;
    this.setLayout(new GridLayout(board.getBoard().length, board.getBoard()[0].length));
    onCreate();
}

private void onCreate() {
    for (int i = 0; i < board.getBoard().length; i++) {
        for (int j = 0; j < board.getBoard()[i].length; j++) {
            this.add(board.getBoard()[i][j]);
        }
    }

    frame.add(this);
    frame.setSize(width, height);
    frame.setMinimumSize(this.minFrameSize);
    frame.setPreferredSize(new Dimension(this.width, this.height));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

GUI 类 JPanel 是否拦截 MouseClick 事件,阻止按钮接收点击事件?

【问题讨论】:

    标签: java swing awt jbutton mouselistener


    【解决方案1】:

    当一个按钮被点击时(无论你用什么来点击它,包括键盘),它都会触发一个 ActionEvent。您应该使用 ActionListener 而不是 MouseListener。

    阅读Swing tutorial

    扩展 Swing 组件也是不好的做法。你应该使用它们。一个按钮不应该听自己的。按钮的用户应该监听按钮事件。

    【讨论】:

    • 我刚刚更改了我的代码,但它仍然无法正常工作。我用 MouseListener 替换了 ActionListener,然后用以下内容覆盖了 actionPerformed:@Override public void actionPerformed(ActionEvent e) { System.out.println("Clicked");仍然没有打印到控制台。感谢您的回复。
    • 查看@Harlandraka 的答案。它解释了原因。
    【解决方案2】:

    它不会触发,因为您没有将侦听器分配给按钮:

    public Tile(int type, int xCoord, int yCoord) {
        this.type = type;
        this.xCoord = xCoord;
        this.yCoord = yCoord;
        addMouseListener(this); // add this line and it should work
    }
    

    但是,如果你只是想听点击,你应该使用 ActionListener 而不是 MouseListener

    【讨论】:

    • @Jamie An ActionListenerMouseListener 上的JButton 更合适
    猜你喜欢
    • 2021-07-27
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2019-01-16
    相关资源
    最近更新 更多