Shows how to drag different names from a list and how to drop
them onto nodes of the graph. The names will be assigned to the labels of regarding nodes.
Showcase: Add one or more nodes to the graph (left mouse-button). Afterward drag one of the names from the left placed tree-view and drop the name on to a previously created node.
package demo.view.advanced;
import demo.view.DemoBase;
import y.base.Node;
import y.view.HitInfo;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
public class DragNamesDemo extends DemoBase {
public DragNamesDemo() {
final JTree tree = new JTree();
tree.setDragEnabled(false);
contentPane.add(new JScrollPane(tree), BorderLayout.WEST);
final DragSource dragSource = new DragSource();
dragSource.createDefaultDragGestureRecognizer(
tree,
DnDConstants.ACTION_COPY,
new DragGestureListener() {
public void dragGestureRecognized(final DragGestureEvent event) {
final Point p = event.getDragOrigin();
final TreePath path = tree.getClosestPathForLocation(p.x, p.y);
if (path != null) {
final Object o = path.getLastPathComponent();
dragSource.startDrag(
event,
DragSource.DefaultCopyDrop,
new StringSelection(o.toString()),
null);
}
}
});
new DropTarget(view, new DropTargetListener() {
public void dragEnter(final DropTargetDragEvent dtde) {
}
public void dragOver(final DropTargetDragEvent dtde) {
}
public void dropActionChanged(final DropTargetDragEvent dtde) {
}
public void drop(final DropTargetDropEvent dtde) {
final Point p = dtde.getLocation();
final HitInfo hit = new HitInfo(view, view.toWorldCoordX(p.x), view.toWorldCoordY(p.y), true, HitInfo.NODE);
if (hit.hasHitNodes()) {
final Node node = hit.getHitNode();
final Transferable t = dtde.getTransferable();
try {
final String text = (String) t.getTransferData(DataFlavor.stringFlavor);
view.getGraph2D().getRealizer(node).setLabelText(text);
view.updateView();
dtde.acceptDrop(DnDConstants.ACTION_COPY);
} catch (UnsupportedFlavorException e) {
dtde.rejectDrop();
} catch (IOException e) {
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
public void dragExit(final DropTargetEvent dte) {
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
initLnF();
(new DragNamesDemo()).start();
}
});
}
} |