Search code examples
imagejavafxfxmlscenebuildergridpane

Java-FX How to set image in a GridPane on click - game Othello


Hi i'm trying to click on a position (from 0 to 7) in my GridPane. I would set an image inside it. I tryed everything but i can't see any improvement...

This is my board enter image description here

Here my code on click on grid

@FXML
   private void clickGrid(MouseEvent event) {
      myGrid = new GridPane();
      black = new Image("othello/images/black.png");
      white = new Image("othello/images/white.png");
      empty = new Image("othello/images/empty.png");

      Node source = (Node)event.getSource() ;
      Integer colIndex = GridPane.getColumnIndex(source);
      Integer rowIndex = GridPane.getRowIndex(source);
      System.out.printf("Mouse clicked cell [%d, %d]%n", colIndex.intValue(), rowIndex.intValue());

      myGrid.add(new ImageView(white), colIndex, rowIndex);

   }

Here my code when i click restart

 @FXML
   private void restartGame(ActionEvent event)throws Exception{
      myGrid = new GridPane();
      black = new Image("othello/images/black.png");
      white = new Image("othello/images/white.png");
      empty = new Image("othello/images/empty.png");
      for (int i = 0; i < 8; i++){ //Per righe
      for (int j = 0; j < 8; j++){ // Per colonne
      myGrid.add(new ImageView(empty), i, j);
      }

      }
      myGrid.add(new ImageView(black), 3, 3);
      myGrid.add(new ImageView(black), 4, 3);
      myGrid.add(new ImageView(white), 4, 4);
      myGrid.add(new ImageView(white), 4, 3);
   }

black is my piece colored of black, for white is white.

Source path

I have main project in src of netbeans.
Inside it, i have:
- othello (it contains my main)
- othello.images (it cointains all my image also backgrounds)
- othello.view (it contains my FXML files)
- othello.model (now nothing)
- othello.controller (it contains the controllers about the fxml files)

Solution

  • Don't create a new GridPane on every click:

    myGrid = new GridPane(); // delete this
    

    delete this line, and add an image to the GridPane you've prepared in FXML