Skip to content
Advertisement

Relative coordinates of a click in Vaadin

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?

Advertisement

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement