JavaFX矩形mouseonclick网格返回

时间:2017-02-05 15:45:48

标签: java oop javafx return

我正在写一个20x20网格的棋盘游戏。

这是我的董事会成员:

private final Position[][] grid = new Position[GRID_SIZE][GRID_SIZE];

每个职位都有:

public class Position {

    private final Coordinates pos;
    private Player player;

    private final static double RECTANGLE_SIZE = 40.0;
    private final Rectangle rect = new Rectangle(RECTANGLE_SIZE, RECTANGLE_SIZE);
}

所以基本上我有20x20个位置,每个位置都有一个矩形

这是我显示网格的方法

for (int cols = 0; cols < GRID_SIZE; ++cols) {
    for (int rows = 0; rows < GRID_SIZE; ++rows) {
        grid.add(gameEngine.getBoard().getGrid()[cols][rows].getRect(), cols, rows);
    }
}

无论如何,网格已初始化并正常运行。我想要做的是使矩形对象可以点击,并且能够在点击它们时返回它们的坐标。

这就是我处理鼠标点击的方式

private void setUpRectangle() {
    rect.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            rect.setFill(Color.BLACK);
        }
    });
}

此代码的作用是将矩形的颜色更改为黑色,但我如何返回坐标。 基本上,我可以编辑onclick函数来返回这个位置的坐标,但是我怎样才能在以后获取它们呢?

2 个答案:

答案 0 :(得分:0)

这不是JavaFX问题,而是设计问题。你有一个容器(Position)有2个对象(CoordinatesRectangle),你希望其中一个知道另一个。也就是说,矩形应该知道其位置的坐标。

这里有一些方法,根据更大的图片,一个可能比其他方法更好。 James_D在comment中提到了一对夫妇。

  1. 在矩形对象中保留位置对象的引用。如果矩形需要从各个位置访问容器中的各种数据,这非常有用。您可以执行rectangle.getPosition().getCoordinates().getPlayer()
  2. 之类的操作
  3. 在矩形对象中保留坐标对象的引用。如果您只需要该对象,这是一个非常有用的方法。您可以执行rectangle.getCoordinates()
  4. 之类的操作
  5. 将坐标传递给setUpRectangle方法。如果矩形不需要从各个位置访问此数据,这非常有用,它是本地解决方案。然后在handle方法中,您将返回传递给setUpRectangle的坐标,但我们无法看到此方法所在的类。
  6. 使用外部帮助。您可以保留Map<Rectangle, Coordinates>之类的内容,然后拨打map.get(rectangle)。您可以在方法Coordinates getCoordinatesForRectangle(Rectangle rectangle)中隐藏此地图,而不是直接调用它。

答案 1 :(得分:0)

您可以将此数据存储为userData(或使用properties,以防userData保留给您的程序中的其他内容):

private final Rectangle rect;

public Position() {
    rect = new Rectangle(RECTANGLE_SIZE, RECTANGLE_SIZE);
    rect.setUserData(this);
}
rect.setOnMouseClicked((MouseEvent event) -> {
    Position pos = (Position) ((Node) event.getSource()).getUserData();
    ...
});

您还可以使用了解位置的监听器:

class CoordinateAwareListener implements EventHandler<MouseEvent> {
    private final int coordinateX;
    private final int coordinateY;

    public CoordinateAwareListener(int coordinateX, int coordinateY) {
        this.coordinateX = coordinateX;
        this.coordinateY = coordinateY;
    }

    @Override
    public void handle(MouseEvent event) {
        // do something with the coordinates
    }

}
相关问题