views:

330

answers:

2

Hello fellow programmers!

I'm having some problems I just can't figure out... I'm writing a Swing Java application with a JList that accepts drag-and-drops. I want to change the cursor while dragging a file or folder from my system over the Java application.

I've spent hours searching google but I've found nothing useful so far. Maybe some of you guys/girls can help me!

Thanks in advance

  • Gianni
A: 

The following will only change the cursor when the user has moved the mouse over your JList.

You can change the cursor when you mouse over a component (i.e. your JList) by using a mouse listener and the setCursor method.

Essentially just add the mouse listener to your JList and use setCursor to change the cursor when the user mouses over the component in your application (mouseEntered and mouseExit). You may also need to do a little inquiry on your drag and drop code to only change the cursor when something valid is being dragged into your JList.

Hope this helps a bit.

Clinton
Well, I tried that. But the MouseListener won't register when dragging a file or folder over the JList. Even though the Java application is at the foreground and 'selected'.Thanks.
Gianni
@Gianni - by "won't register", you mean it doesn't recieve any events?
Clinton
Indeed. It won't 'trigger' the mouseover event.
Gianni
+1  A: 

I've found it myself... Thanks Clinton for answering though. Here's what I've used:

first create the JList... You all know how to do that... Then I've added a setDropTarget:

lstFiles.setDropTarget(new DropTarget()
{
    @Override
    public synchronized void drop(DropTargetDropEvent dtde) 
    {
     this.changeToNormal();
     //handle the drop... [...]
    }

    @Override
    public synchronized void dragEnter(DropTargetDragEvent dtde) 
    {
     //Change cursor...
     Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
     setCursor(cursor);

     //Change JList background...
     lstFiles.setBackground(Color.LIGHT_GRAY);
    }

    @Override
    public synchronized void dragExit(DropTargetEvent dtde) 
    {
     this.changeToNormal();
    }

    private void changeToNormal()
    {
     //Set cursor to default.
     Cursor cursor = new Cursor(Cursor.DEFAULT_CURSOR);
     setCursor(cursor);

     //Set background to normal...
     lstFiles.setBackground(Color.WHITE);
    }
});
Gianni
Ah-ha! Nice work!
Clinton