J
Not much testing, but for standard situations, it's like, import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Pair;
import java.util.Arrays;
public class Main extends Application {
/**
* Все элементы одной строки имеют одинаковое свойство minY. Значит каждое уникальное значение соответсвует
* одной строке.
* @param gridPane Исходная панель
* @return Отсортированный по возрастанию массив Y координат строк.
*/
private static double[] getRowsY(final GridPane gridPane) {
return gridPane.getChildren().stream()
.mapToDouble(node -> node.getBoundsInParent().getMinY())
.distinct().sorted().toArray();
}
/**
* В рамках одной строки, каждый элемент имеет уникальное свойство minX.
* @param gridPane Исходная панель
* @param rowMinY Координата minY строки, для которой получаем координаты minX элементов
* @return Отсортированный по возрастанию массив X координат элементов строки.
*/
private static double[] getColumnsX(final GridPane gridPane, double rowMinY) {
return gridPane.getChildren().stream()
.map(node -> node.getBoundsInParent())
.filter(bounds -> bounds.getMinY() == rowMinY)
.mapToDouble(bounds -> bounds.getMinX())
.distinct().sorted().toArray();
}
/**
* Получение координат элемента
* @param gridPane Исходная панель
* @param node Искомый элемент
* @return Пара (rowIndex, columnIndex) элемента
*/
public static Pair<Integer, Integer> getPosition(final GridPane gridPane, final Node node) {
if (!gridPane.getChildren().contains(node)) {
return null;
}
Bounds boundsInParent = node.getBoundsInParent();
double[] rowsY = getRowsY(gridPane);
int rowIndex = Arrays.binarySearch(rowsY, boundsInParent.getMinY());
double[] columnsX = getColumnsX(gridPane, boundsInParent.getMinY());
int columnIndex = Arrays.binarySearch(columnsX, boundsInParent.getMinX());
return new Pair<>(rowIndex, columnIndex);
}
public void start(Stage primaryStage) {
GridPane gridPane = new GridPane();
final Label searched = new Label("1-2");
final Label fail = new Label("Fail");
gridPane.addRow(0, new Label("0-0"), new Label("0-1"), new Label("0-2"));
gridPane.addRow(1, new Label("1-0"), new Label("1-1"), searched);
gridPane.addRow(2, new Label("2-0"), new Label("2-1"), new Label("2-2"));
primaryStage.setScene(new Scene(gridPane, 100, 100));
primaryStage.show();
System.out.println(getPosition(gridPane, fail));
System.out.println(getPosition(gridPane, searched));
System.out.println(getPosition(gridPane, gridPane.getChildren().get(6)));
}
}