有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将eventListener的结果存储为对象?

我有一些鼠标事件,我用它们在画布上画盒子。我创建了一个BoundingBox类,它包含一个构造函数和get set方法,其中包含x和y坐标,以及要在画布上绘制的框的宽度和高度。然而,由于我有几个鼠标事件(到目前为止我只做了mouseDown),我不知道应该如何存储它们。到目前为止,我的mouseDown事件在单击时创建了一个Div,其中包含x-y坐标,但还没有宽度和高度,因为我还无法绘制方框。请注意,我使用的是Vaadin框架,谢谢

以下是我的mouseDown eventListener:

element.addEventListener("mousedown", event -> {  // Create a Div on Click

            Element boundingBoxResult = ElementFactory.createDiv();
            element.appendChild(boundingBoxResult);

            JsonObject evtData = event.getEventData();

            double xcoordi = evtData.getNumber("event.x");
            double ycoordi = evtData.getNumber("event.y");
            boundingBoxResult.setAttribute("data-x", String.format("%f", xcoordi));
            boundingBoxResult.setAttribute("data-y", String.format("%f", ycoordi));

边界框类:

package com.vaadin.starter.beveragebuddy.ui.components;

public class BoundingBox {

    private double xcoordi;
    private double ycoordi;
    private double width;
    private double height;

    public BoundingBox(double xcoordi, double ycoordi, double width, double height) {
        this.xcoordi = xcoordi;
        this.ycoordi = ycoordi;
        this.width = width;
        this.height = height;
    }


    public double getXcoordi() {
        return xcoordi;
    }

    public void setXcoordi(double xcoordi) {
        this.xcoordi = xcoordi;
    }

    public double getYcoordi() {
        return ycoordi;
    }

    public void setYcoordi(double ycoordi) {
        this.ycoordi = ycoordi;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }
}

是否会有更好的替代方案(比如将它们存储在ArrayList中),因为我将在未来绘制多个框,这意味着我必须保存许多坐标。非常感谢您的帮助,谢谢


共 (1) 个答案

  1. # 1 楼答案

    我不确定以后如何使用它们,但可以将它们存储在父类中的一个变量中(即添加侦听器的位置)。比如:

    List<Element> results = new ArrayList<>();
    
    // ...
    
    element.addEventListener("mousedown", event -> {  // Create a Div on Click
            Element boundingBoxResult = ElementFactory.createDiv();
            results.add(boundingBoxResult)
    
            // ...
    }
    

    然后,该列表与您的父实例(也是一个div?)一样存在做请记住,如果您对这样的元素有自己的簿记,您可能还需要在某个时候清除它