java - JButton MouseListener 没有响应

标签 java swing awt jbutton mouselistener

我正在尝试构建一款扫雷类型的游戏,更具体地说是 MSN 游戏中常见的两人游戏。我有一个 Tile 对象的多维数组。每个图 block 都有一个状态(地雷、空白或相邻地雷的数量)。我有一个 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 事件,从而阻止按钮接收单击事件?

最佳答案

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

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

关于java - JButton MouseListener 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482394/

相关文章:

java - 对简单的 While 循环感到困惑 - 躲在 table 下面

java - Swing 文本字段方向

java - 将Keylistener添加到全屏JWindow

java - 使用 Java 连接到 Oracle 数据库

java - 迭代 Collection,避免在循环中删除对象时出现 ConcurrentModificationException

java - 如何让我的时间戳变量显示正确的日期?

java - java中图形不绘制图像

java - 图像不会绘制到动画

Java Choice 选定索引未正确返回

java - 如何将图像向左(或向右)移动?