0

I'm trying to figure out where the mouse is, in terms of a GridPane's column and row. I know the mouse position, so I could presumably figure it out from that, if I knew each cell's width and height (which I don't see an easy way to figure out) but most of the code I've seen seems to presume the mouse is over a node inside the GridPane:

        Node node = (Node) event.getTarget();
        int row = GridPane.getRowIndex(node);
        int column = GridPane.getColumnIndex(node);

But I actually don't have anything inside my GridPane, so I just get the whole GridPane. Now, I suppose I could add nodes for each of the cells, but this seems inefficient. (The idea is that the user is placing the nodes in a grid, so the grid starts out empty.)

Edit: To clarify, I basically want to do what SceneBuilder does when you place a GridPane down and then drag a component over it. The cell you're hovering over is highlighted and then (if you drop the component) it gets added to that cell. So I know it's possible (and also not outlandish as a concept).

Any thoughts?

user3810626
  • 6,798
  • 3
  • 14
  • 19
  • 1
    why, what do want to achieve? the "grid" is just a mental image of the layout, nothing real – kleopatra Apr 22 '21 at 09:21
  • 1
    If you want to respond to mouse events, you should have a node on which those events happen. Create e.g. a blank pane for that purpose if you need. – James_D Apr 22 '21 at 13:23
  • @kleopatra The image isn't just mental: Think of what I want to do like SceneBuilder. Actually exactly like SceneBuilder. When you drag a button over a grid cell, that cell indicates and the button goes in that cell. That's exactly what I have in mind. – user3810626 Apr 22 '21 at 18:00
  • For further clarification: I don't want to create N blank nodes just so I can drop something on them. Maybe there's a better object than a GridPane for it, but I want to do exactly what SceneBuilder does. – user3810626 Apr 22 '21 at 18:10

1 Answers1

0

This doesn't exactly answer my question but it's useful for me short term and it might be useful for others. It works only when the cells are uniform across the dimension being queried (i.e., all the same width/height).

 public int getCoord(double width, double coord, int numberOfSections) {
        long dim = Math.round(width / numberOfSections);
        long border = dim;
        int val = 0;
        while(coord > border) {
            border += dim;
            val++;
        }
        return val;
    }

Lacking a way to directly iterate over the current state of rows and columns, I think the full solution requires an analysis of children (if there are any) and the row and column constraints.

user3810626
  • 6,798
  • 3
  • 14
  • 19