Relative coordinates of a click in Vaadin

Tags: ,



I’m building an app with Vaadin 14 where the user is required to click an image and the coordinates from that click are then further processed. Vaadin seems to only offer click coordinates relative to the user’s screen or browser. My app needs the coordinates to be relative to the component. Is there a way to accomplish this?

Answer

The answer was to go through the Element API and use image.getElement().addEventListener("click", ...).addEventData(...) and thus pass the necessary info from browser to the server.

In my case:

Image image = ...
image.getElement().addEventListener("click", this::handleClick)
                .addEventData("event.offsetX")
                .addEventData("event.offsetY");

private void handleClick(DomEvent event) {
        JsonObject eventData = event.getEventData();
        double x = eventData.getNumber("event.offsetX");
        double y = eventData.getNumber("event.offsetY");

        String text = "X: " + x + ", Y: " + y;
        System.out.println(text);
    }

More info: https://vaadin.com/docs/v14/flow/element-api/tutorial-event-listener



Source: stackoverflow