簡體   English   中英

當鼠標在應用程序窗口之外時,是否可以在從搖擺中拖動(我的意思是圖像,而不是位置)時更改鼠標光標?

[英]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 application ,在windows支持之間drag&drop

我想全局更改mouse cursor 即使它是在application windows之間。

最明顯的解決方案是Component.setCursor()調用component ,它開始drag或在主window上不起作用。

然后,只有我發現這樣做而不使用原生的,平台相關的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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM