在 JavaFX 中让棋子转到您想要的磁贴?

Having a checker piece go to the tile you want it to in JavaFX?

我目前正在创建一个跳棋类型的游戏,虽然我可以让方块在您每次点击它们时向上、向下移动等,但当涉及到点击棋子然后点击方块时,我处于不知道如何让它发挥作用。

这是棋子和棋盘的事件处理程序

class CircleEventHandler implements EventHandler<MouseEvent>{
    int Crow;
    int Ccol;
    @Override
    public void handle(MouseEvent event) {
        System.out.println("Mouse Clicked");

        Circle c = (Circle)event.getSource();
        Crow = gp.getRowIndex(c);
        Ccol = gp.getColumnIndex(c);
        System.out.println("row is " + Crow + " & col is " + Ccol);

        gp.getChildren().remove(c);


    }

}

class RectangleEventHandler implements EventHandler<MouseEvent>{

    @Override
    public void handle(MouseEvent event) {

        Rectangle r = (Rectangle)event.getSource();
        int row = gp.getRowIndex(r);
        int col = gp.getColumnIndex(r);
        System.out.println("row is " + row + " & col is " + col);

        gp.add(c, row, col);


    }

}

运行 这段代码会给我一个空指针异常,并指向矩形事件处理程序中的 "gp.add(c, row, col);"。我不确定如何让它工作,有人可以指出我正确的方向吗?

你可以,例如使这些处理程序 类 成为内部 类 并将数据保存在封闭的实例中以使其工作。

以下示例仅演示如何根据之前单击的圆圈的颜色重新着色矩形,但它应该演示如何传递信息。

public class Board {

    public Board(GridPane grid) {
        this.grid = grid;
    }

    private final GridPane grid;
    private Circle selectedCircle;

    public class CircleEventHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent event) {
            // store info about circle clicked in enclosing instance
            selectedCircle = (Circle) event.getSource();
        }

    }

    public class RectangleEventHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent event) {

            if (selectedCircle != null) {
                // use field of enclosing instance to retrieve color of the circle
                Rectangle r = (Rectangle) event.getSource();
                r.setFill(selectedCircle.getFill());
                selectedCircle = null;
            }

        }

    }

}
@Override
public void start(Stage primaryStage) {
    GridPane root = new GridPane();
    root.addRow(0, new Circle(50, Color.GREEN), new Circle(50, Color.YELLOW), new Circle(50, Color.RED));
    root.addRow(1, new Rectangle(50, 50), new Rectangle(50, 50), new Rectangle(50, 50));

    Board board = new Board(root);

    EventHandler<MouseEvent>[] handlers = new EventHandler[] {
        board.new CircleEventHandler(),
        board.new RectangleEventHandler()
    };

    for (Node n : root.getChildren()) {
        n.setOnMouseClicked(handlers[GridPane.getRowIndex(n)]);
    }

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

至于在您的代码中查找 NPE 的来源:没有更多信息这是不可能的,因为没有关于为什么 gp 为空的信息。