当鼠标在应用程序外部 window 时,从 swing 拖动(我的意思是图像,而不是位置)时是否可以更改鼠标光标?

Is it possible to change mouse cursor when dragging (I mean image, not position) from swing when mouse is outside application window?

我有 multi-window java swing applicationdrag&dropwindows 之间支持。

我想 mouse cursor 全局 更改,即使它介于 application windows 之间。

最明显的解决方案是 Component.setCursor() 在开始 drag 或主要 window 上调用的 component 不起作用。

然后我发现在不使用本机、平台相关 api 的情况下执行此操作的唯一方法是使用 java Swing 的 DnD api,它允许您在拖动时设置自定义鼠标光标

import javax.swing.*;

import java.awt.Cursor;
import java.awt.datatransfer.StringSelection;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;

public class DndExample extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DndExample());
    }

    public DndExample() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel dragLabel = createDndLabel();
        getContentPane().add(dragLabel);
        pack();
        setVisible(true);
    }

    private JLabel createDndLabel() {
        JLabel label = new JLabel("Drag me, please");


        DragGestureListener dragGestureListener = (dragTrigger) -> {
            dragTrigger.startDrag(new Cursor(Cursor.HAND_CURSOR), new StringSelection(label.getText()));
        };

        DragSource dragSource = DragSource.getDefaultDragSource();
        dragSource.createDefaultDragGestureRecognizer(label, DnDConstants.ACTION_COPY, dragGestureListener);

        return label;
    }
}