-1
我在跳棋游戏中获得了几个典当物。我希望能够对每个人(圈子)都采取行动,而不必为每个棋子设置24个不同的动作。有什么想法?设置为典当行为
我在跳棋游戏中获得了几个典当物。我希望能够对每个人(圈子)都采取行动,而不必为每个棋子设置24个不同的动作。有什么想法?设置为典当行为
使用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);
}
}
在阵列中使用的循环和存储跳棋? –
“没有为每个棋子设置24个不同的动作。为什么不?只需在循环中调用'setOnAction'即可。 –