tuomasss
tuomasss

Reputation: 81

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?

Upvotes: 4

Views: 508

Answers (1)

tuomasss
tuomasss

Reputation: 81

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

Upvotes: 4

Related Questions