簡體   English   中英

JavaFX矩形mouseonclick網格返回

[英]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個對象( CoordinatesRectangle )的容器( Position ),並且您希望它們中的一個了解另一個。 也就是說,矩形應該知道其位置的坐標。

這里有幾種方法,根據整體情況,一種方法可能比其他方法更好。 James_D在評論中提到了一對夫婦。

  1. 在矩形對象中保留位置對象的引用。 如果矩形需要從各個位置訪問容器中的各個基准,則此功能很有用。 您將執行諸如rectangle.getPosition().getCoordinates().getPlayer()
  2. 在矩形對象中保留坐標對象的引用。 如果只需要該對象,則這是一種更具體的方法(1)很有用。 您可能會做類似rectangle.getCoordinates()
  3. 將坐標傳遞給您的setUpRectangle方法。 如果您的矩形不需要從各個地方訪問此數據,這將非常有用,這是一種本地解決方案。 然后,在handle方法中,您將返回傳遞給setUpRectangle的坐標,盡管我們看不到此方法所在的類。
  4. 使用外部幫助。 您可以保留類似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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM