[英]JavaFX rectangle mouseonclick grid 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函数以返回该位置的坐标,但是以后如何获取它们呢?
这不是JavaFX问题,而是设计问题。 您有一个包含2个对象( Coordinates
和Rectangle
)的容器( Position
),并且您希望它们中的一个了解另一个。 也就是说,矩形应该知道其位置的坐标。
这里有几种方法,根据整体情况,一种方法可能比其他方法更好。 James_D在评论中提到了一对夫妇。
rectangle.getPosition().getCoordinates()
或.getPlayer()
。 rectangle.getCoordinates()
。 setUpRectangle
方法。 如果您的矩形不需要从各个地方访问此数据,这将非常有用,这是一种本地解决方案。 然后,在handle
方法中,您将返回传递给setUpRectangle
的坐标,尽管我们看不到此方法所在的类。 Map<Rectangle, Coordinates>
,然后调用map.get(rectangle)
。 您可以使用Coordinates getCoordinatesForRectangle(Rectangle rectangle)
方法隐藏此地图,而不是直接调用它。 您可以将这些数据存储为userData
(或在程序中为其他内容保留userData
情况下使用properties
):
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.