aperkins
aperkins

Reputation: 13124

How to get mouse information during drag and drop in Java?

We have a request on a product I am working on to get more feedback on our drag and drop behavior. Specifically, they would like us to highlight certain areas when the mouse is over them during the drag operation (to show where the drop will occur). However, we are using a TransferHandler to handle both DnD, and cut/copy/paste, and based on what we have tested it seems that Swing will not let us add another DropTarget to the component (in retrospect, for some obvious reasons!) We have attempted to go down a few paths, none of which have born any fruit.

Basically, we would like to get in the middle of the dragEnter and dragExit events while still using the TransferHandler capabilities to facilitate easy Cut/Copy/Paste and drop behavior. Does anyone have any examples to do this kind of thing? Or is this just really hard to do in the current setup of DnD in Swing?

Upvotes: 5

Views: 1014

Answers (1)

gcooney
gcooney

Reputation: 1699

Most out-of-the-box Swing components have support for this built in(JTree, JList, etc). For those components you can set the drop mode and the ui will handle drawing the appropriate visual effects.

myJList.setDropMode(DropMode.ON_OR_INSERT);

For a custom component you need to handle the drawing yourself by overriding paintComponent to draw the custom effects and then adding a propertyChangeListener for the "dropLocation" property that triggers the appropriate repaints when necessary. This will get called frequently on drag so you may wish to only trigger repaints when the change in drop location actually results in a change in behavior.

Swing Tutorial on Drop Location Rendering

Upvotes: 2

Related Questions