使用javafx获取鼠标坐标

时间:2018-07-13 16:06:30

标签: java javafx

我有一个程序可以制作一个带有数字的网格。我按一个数字,我可以得到我所在的单元格,但是我希望能够在单击其中一个数字时打印鼠标的坐标。因为那时,我想访问javafx程序另一个场景中的那个位置。

public class Grid extends Application {

    private static final int TILE_SIZE = 40;
    private static final int W = 800;
    private static final int H = 600;

    private static final int X_TILES = W / TILE_SIZE;
    private static final int Y_TILES = H / TILE_SIZE;

    private Tile[][] grid = new Tile[X_TILES][Y_TILES];
    private Scene scene;

    private Parent createContent() {
        Pane root = new Pane();
        root.setPrefSize(W, H);
        int num = 1;
        for (int y = 0; y < Y_TILES; y++) {
            for (int x = 0; x < X_TILES; x++) {
                Tile tile = new Tile(x, y, String.valueOf(num));
                num++;
                grid[x][y] = tile;
                root.getChildren().add(tile);
            }
        }

        return root;
    }

    private class Tile extends StackPane {
        private int x, y;
        private boolean isClick = false;

        private Rectangle border = new Rectangle(TILE_SIZE - 2, TILE_SIZE - 2);

        private Text text = new Text();
        private String num;

        public Tile(int x, int y, String num) {
            this.x = x;
            this.y = y;
            this.num = num;

            border.setFill(Color.TRANSPARENT);
            border.setStroke(Color.LAVENDER);

            text.setFont(Font.font(18));
            text.setText(num);
            text.setVisible(true);

            getChildren().addAll(border, text);

            setTranslateX(x * TILE_SIZE);
            setTranslateY(y * TILE_SIZE);

            setOnMouseClicked(e -> open());
        }

        public void open() {
            if (isClick)
                return;

            isClick = true;
//            text.setVisible(true);
            border.setFill(null);
            System.out.println(this.num+" - ("+this.x +", " +this.y+")");

        }
    }

    //...launch code
}

我正在尝试放置类似这样的内容,但是我什至无法编译它。我应该将其放在createContent()还是Tile构造器中?

 root.setOnMouseClicked(new EventHandler<MouseEvent>() {  
            public void handle(MouseEvent event) {
                  double newX = event.getX(); 
                  double newY = event.getY(); 

                  System.out.println(newX+newY);

              }
  });

0 个答案:

没有答案