Is it possible to change mouse cursor when dragging (I mean image, not position) from swing when mouse is outside application window?
I have multi-window java swing application
with drag&drop
between windows
support.
I'd like to change mouse cursor
globally even if it is between application windows
.
The most obvious solution which is Component.setCursor()
called on component
which starts drag
or on the main window
does not work.
Solution 1:
Then only way I found to do this without using native, platform-dependent api is to use java Swing's DnD api which allows You to set custom mouse cursor when dragging
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;
}
}