2017-05-18 51 views
-1

我在跳棋遊戲中獲得了幾個典當物。我希望能夠對每個人(圈子)都採取行動,而不必爲每個棋子設置24個不同的動作。有什麼想法?設置爲典當行爲

+2

在陣列中使用的循環和存儲跳棋? –

+1

「沒有爲每個棋子設置24個不同的動作。爲什麼不?只需在循環中調用'setOnAction'即可。 –

回答

1

使用getChildren()方法獲取父節點中的所有棋子並將其存儲在列表中,然後迭代它並按如下方式調用setOnAction。

List<Node> chieldNode = new ArrayList<>(); 
     chieldNode = parentNode.getChildren(); 
    for (Node node : chieldNode) { 
     if (node instanceof Button) { 
      ((Button) node).setOnAction(e -> { 
       System.out.println(((Button) node).getText()); 
      }); 
     } 
} 

或者參考下面的例子得到一些想法

public class DemoEx extends Application { 
     @Override 
     public void start(Stage primaryStage) throws Exception { 
       GridPane gridPane = new GridPane(); 
       Button[] button = new Button[100]; 
       for (int i = 0; i < 10; i++) { 
        for (int j = 0; j < 10; j++) { 
         button[j] = new Button(i + "" + j); 
         button[j].setPrefSize(50, 50); 
         gridPane.add(button[j], i, j); 
        } 
       } 

       List<Node> chieldNode = new ArrayList<>(); 
       chieldNode = gridPane.getChildren(); 
       for (Node node : chieldNode) { 
        if (node instanceof Button) { 
         ((Button) node).setOnAction(e -> { 
          System.out.println(((Button) node).getText()); 
         }); 
        } 
       } 

       Scene scene = new Scene(gridPane, gridPane.getMaxHeight(), gridPane.getMaxWidth()); 
       primaryStage.setScene(scene); 
       primaryStage.show(); 
      } 
     public static void main(String args[]) { 
      launch(args); 
     } 
    }