Search code examples
javabuttonjavafximageviewminesweeper

Adding image to a Button in JavaFX after Button is created


I am working on coding a MineSweeper game using JavaFx. I am having an issue with changing the Buttons to just include an image and not have text. A portion of my code is as follows:

ImageView bomb;
Image bombImage = new Image(MineSweeper.class.getResourceAsStream("images/bomb.png"));
bomb = new ImageView(bombImage);
boolean[][] mineField = new boolean[row][column];
for (int i = 0; i < numMines; i++) {
    int indexRow = isMine.nextInt(row);
    int indexCol = isMine.nextInt(column);
    System.out.println("row: " + indexRow + ", column: " + indexCol);
    mineField[indexRow][indexCol] = true;
}

for (int i = 0; i < row; i++) {
    for (int j = 0; j < column; j++) {
        System.out.println("" + mineField[i][j]);
        if (mineField[i][j] == true) {
            board[i][j].setText("");
            board[i][j].setGraphic(bomb);


        } else {
            board[i][j].setText("Nope!");
        }

    }
}

This is not how the actual game will work. But I was wanting to check if I could add the image of the bomb to the buttons that contain a mine. When I run the code there is only one image of a mine that shows up and the other buttons just have empty text or say "Nope!." If I cannot figure out how to add an image to a button then I will not be able to actually continue with the programming of the game. I have decided that I want to build this game from scratch and not use Scene Builder. I appreciate any advice.


Solution

  • The reason for only one image is displayed that you cannot use the same ImageView as graphic for two Button objects.

    An optional icon for the Labeled. This can be positioned relative to the text by using setContentDisplay(javafx.scene.control.ContentDisplay). The node specified for this variable cannot appear elsewhere in the scene graph, otherwise the IllegalArgumentException is thrown. See the class description of Node for more detail.

    Modify this line ...

    board[i][j].setGraphic(bomb);
    

    ... to ...

    board[i][j].setGraphic(new ImageView(bombImage ));
    

    This will create a new ImageView object for all of your Buttons.