You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin 24拖拽功能无法触发Drop事件,求排查解决

Vaadin 24拖拽功能不触发Drop事件的问题解决

你代码的核心问题是没有为DragSource设置拖拽数据。在Vaadin 24中,仅创建DragSource实例并设置允许的效果是不够的,必须显式指定要传递的拖拽数据,否则DropTarget无法识别该拖拽操作的合法性,从而不会触发drop事件。

修改方案

在创建DragSource后,添加setData方法设置拖拽数据,示例如下:

public DashboardView() {

    System.out.println("View loaded!");

    // Drag-Quelle
    Div dragSourceDiv = new Div(new Text("Drag me!"));
    dragSourceDiv.getStyle()
            .set("padding", "20px")
            .set("background-color", "lightgray")
            .set("cursor", "grab");
    DragSource<Div> dragSource = DragSource.create(dragSourceDiv);
    dragSource.setEffectAllowed(EffectAllowed.MOVE);
    // 添加这行:设置拖拽数据,类型可自定义,这里用text/plain示例
    dragSource.setData("text/plain", dragSourceDiv.getText());
    dragSource.addDragStartListener(event -> System.out.println("Drag started!"));

    // Drop-Ziel
    Div dropTargetDiv = new Div();
    dropTargetDiv.setWidth("300px");
    dropTargetDiv.setHeight("300px");
    dropTargetDiv.getStyle()
            .set("border", "3px dashed blue")
            .set("background-color", "yellow");
    DropTarget<Div> dropTarget = DropTarget.create(dropTargetDiv);
    dropTarget.setDropEffect(DropEffect.MOVE);
    dropTarget.addDropListener(event -> {
        System.out.println("Drop-Event!");
        event.getDragSourceComponent().ifPresent(source -> {
            System.out.println("Widget dropped: " + source.getElement().getText());
        });
    });

    add(dragSourceDiv, dropTargetDiv);
}

原因说明

浏览器的原生拖拽机制要求拖拽源必须携带数据,Vaadin的DragSource组件封装了这一机制。如果没有设置拖拽数据,浏览器会认为这是一个无效的拖拽操作,DropTarget不会触发drop事件。通过setData指定数据后,DropTarget才能正确识别并响应拖拽动作。

内容的提问来源于stack exchange,提问作者user1119859

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 22:29:51