-1

I have GridPane that I'm using to create a calendar. When I hover over any of the calendar cells, I want to get the location of that specific cell.

The end goal is to use the location of that cell to access its children and perform operations on them. One specific thing I want to do is create a custom (non-JavaFX) tooltip and move its position in the scene graph to the location of that hovered cell.

Here where I'm at so far

2 Answers2

0

In my opinion, there is no point in knowing which cell your mouse is hovering on. You should instead make the content of each cell into some kind of reusable control.

Example:

public class CellControl extends BorderPane {
    // Your UI logic

    // Getters for data
    public final LocalDate getDate() {
        return date;
    }
}

ObservableList<CellControl> cells = FXCollections.observableArrayList(cell -> new Observable[] {cell.hoverProperty()});

ObjectProperty<CellControl> hoveredCell = new SimpleObjectProperty<CellControl>() {
    @Override protected void invalidated() {
        // Do something
    }
};

hoveredCell.bind(Bindings.createObjectBinding(
        () -> cells.stream().filter(CellControl::isHover).findAny().orElse(null)
    , cells));
Jai
  • 8,165
  • 2
  • 21
  • 52
0

GridPane.getRowIndex and GridPane.getColumnIndex could be used to determine the row/column.

Assuming you don't move the cells simply making the indices/the cell itself available to the listener is usually simpler:

@Override
public void start(Stage primaryStage) {
    GridPane root = new GridPane();

    int row = 0;
    int column = 0;
    for (int i = 0; i < 30; i++) {
        Text text = new Text(Integer.toString(i + 1));
        StackPane cell = new StackPane(text);
        cell.setStyle("-fx-background-color: lightblue; -fx-border-width: 2; -fx-border-color: black; -fx-border-style: solid");
        cell.setMinSize(50, 50);
        root.add(cell, column, row);

        final int rowFinal = row;
        final int columnFinal = column;
        cell.setOnMouseEntered(evt -> {
            System.out.format("column=%d; row=%d; cell=%s\n", columnFinal, rowFinal, cell);
            text.setText(text.getText() + "*");
        });
        cell.setOnMouseExited(evt -> {
            String s = text.getText();
            text.setText(s.substring(0, s.length() - 1));
        });

        column++;
        if (column == 7) {
            column = 0;
            row++;
        }
    }

    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
}
fabian
  • 80,457
  • 12
  • 86
  • 114