(1.4 beta) custom TransferHandler
I'm trying to implement DnD using new Swing mechanism (TransferHandler).
I have JTree-derived class, that I want to drag object associated with tree item from. I've implemented Transferable-derived class for data that I must return in in my tree TransferHandler-derive's createTransferable(). However, I here need to know drag origin point - but I have only JComponent (that is, tree).
Any ideas?
Thanks in advance,
Anton.
[464 byte] By [
hitry] at [2007-9-26 3:26:31]

I am not sure I understood your question, but here goes.
If by 'drag source origin point' you mean a reference to the component where the drag began, then you already have it.
Assuming Foo is the JTree derived class, then in your TransferHandler's createTransferable(JComponent comp) method you can just do
if( comp instanceof Foo)
{
....
}
- vikram
Add a MouseListener to the JTree. You'll get the coordinates from the MousePressed event.
If you want to get the *drop* x,y, it is trickier. You'll need to add a DropTargetListener to the JTree:
try {
getDropTarget().addDropTargetListener([your listener]);
}
catch (TooManyListenersException e) {
e.printStackTrace();
}
and get the point from the DropTargetDropEvent given to the drop() method.
-hope this helps
Juan
I am having problems with it too. Using the code:
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
public class ATree extends JTree {
public ATree() {
this.setTransferHandler(new ATransferHandler());
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
public static void main(String[] args) {
JFrame frame = new JFrame("ATest");
final JTree tree = new ATree();
JScrollPane treeView = new JScrollPane(tree);
frame.getContentPane().add(treeView, BorderLayout.CENTER);
frame.setSize(200,200);
frame.show();
}
protected class ATransferHandler extends TransferHandler{
ATransferHandler(){
super();
}
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors){
System.out.println("Can import called");
return true;
}
public boolean importData(JComponent comp, Transferable t){
System.out.println("Can import called");
return false;
}
}
Now, if I drag an item from the desktop to the tree, can import is only called once, even if I move the drop point over multiple nodes. The importData is called on the JTree with the tree.getCurrentSelection() specified correctly. Technically, the tree is the drop point but in order for the JTree to be useful the canimport method should be called for each node/object in the tree as it is selected during a drag.