【问题标题】:Java-FX How to set image in a GridPane on click - game OthelloJava-FX 如何在单击时在 GridPane 中设置图像 - 游戏奥赛罗
【发布时间】:2017-07-19 19:00:45
【问题描述】:

您好,我正在尝试单击 GridPane 中的某个位置(从 0 到 7)。 我会在里面设置一个图像。我尝试了所有方法,但我看不到任何改进...

这是我的董事会

这是我点击网格的代码

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

   }

这是我点击重启时的代码

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

黑色是我的黑色,因为白色是白色。

源码路径

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)

【问题讨论】:

    标签: image javafx fxml scenebuilder gridpane


    【解决方案1】:

    我认为您看不到新图像,因为您添加到新网格,而不是现有网格:

    myGrid = new GridPane();  // !!! here a problem
    myGrid.add(new ImageView(white), colIndex, rowIndex);
    

    【讨论】:

      【解决方案2】:

      不要在每次点击时都创建一个新的 GridPane:

      myGrid = new GridPane(); // delete this
      

      删除此行,并将图像添加到您在 FXML 中准备的 GridPane 中

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 1970-01-01
        • 2020-12-22
        • 2015-02-09
        • 2012-10-07
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多