Jamie
Jamie

Reputation: 511

JButton MouseListener not responding

I am trying to build a minesweeper type game, more specifically the two player one that used to feature on MSN games. I have a multidimensional array of Tile objects. Each Tile has a state (mine, blank or number of mines adjacent). I have a GUI class that handles all of the front end aspects of the program.

Each Tile extends JButton and implements MouseListener, however when I click on a button it does not fire the MouseClicked method for the corresponding button/tile.

Code is as follows :

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

}

And the GUI class :

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

Does the GUI class JPanel intercept MouseClick events preventing the buttons from receiving the click event?

Upvotes: 0

Views: 1795

Answers (2)

BackSlash
BackSlash

Reputation: 22243

It does not fire because you don't assign the listener to the button:

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
}

However, if you just want to listen clicks, you should use ActionListener instead of MouseListener

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 692121

When a button is clicked (whatever you use to click it, including the keyboard), it fires an ActionEvent. You should use an ActionListener instead of a MouseListener.

Read the Swing tutorial.

It's also bad practice to extends Swing components. You should use them. A button shouldn't listen to itself. The user of the button should listen to the button events.

Upvotes: 3

Related Questions