[英]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.