1 package org.feistymeow.dragdrop;
7 import java.awt.event.*;
9 import javax.swing.event.*;
10 import javax.swing.tree.DefaultMutableTreeNode;
11 import javax.swing.tree.DefaultTreeCellRenderer;
12 import javax.swing.tree.DefaultTreeModel;
13 import javax.swing.tree.DefaultTreeSelectionModel;
14 import javax.swing.tree.MutableTreeNode;
15 import javax.swing.tree.TreeCellRenderer;
16 import javax.swing.tree.TreePath;
17 import javax.swing.tree.TreeSelectionModel;
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21 import org.apache.log4j.PropertyConfigurator;
24 * A demo of the DragonDropHandler being used with a JTree.
26 * @author Chris Koeritz
27 * @copyright Copyright (c) 2012-$now By University of Virginia
28 * @license This file is free software; you can modify and redistribute it under the terms of the
29 * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
31 @SuppressWarnings("serial")
32 public class dragdrop_tree_test extends JFrame implements TreeSelectionListener
34 private DraggableDroppableTree larch;
35 private JTextField fileName;
36 static private Log logger = LogFactory.getLog(dragdrop_tree_test.DraggableDroppableTree.class);
38 public dragdrop_tree_test(String startPath)
40 super("dragdrop_test");
42 // create the tree, configure it to show our hashtable nodes, and put it in
44 larch = new DraggableDroppableTree(startPath);
45 DefaultTreeModel treeModel = (DefaultTreeModel) larch.getModel();
46 larch.setCellRenderer(new CustomCellRenderer());
47 TreeSelectionModel selmod = new DefaultTreeSelectionModel();
48 selmod.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
49 larch.setSelectionModel(selmod);
50 larch.addTreeSelectionListener(this);
51 JScrollPane listScrollPane = new JScrollPane(larch);
52 // get the files that live in the specified directory.
53 String dirName = startPath + "/"; // make sure we think of it as a
55 String filelist[] = new File(dirName).list();
56 MutableTreeNode root_node = (MutableTreeNode) treeModel.getRoot();
57 if (root_node == null) {
58 logger.error("something is not right about tree. has null root.");
61 // load up the tree with the files in the directory they passed.
62 for (int i = 0; i < filelist.length; i++) {
63 String thisFileSt = dirName + filelist[i];
64 File thisFile = new File(thisFileSt);
65 // skip directories for now.
66 if (thisFile.isDirectory())
69 if (filelist[i].startsWith("."))
72 // need to trap exceptions from the URI/URL functions.
73 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(makeNode(
74 thisFile.getName(), thisFile.toURI().toURL().toString(),
75 thisFile.getAbsolutePath()));
76 treeModel.insertNodeInto(newNode, root_node, root_node.getChildCount());
77 } catch (java.net.MalformedURLException e) {
78 logger.warn("caught an exception while trying to process path: "
79 + thisFile.getAbsolutePath());
83 // set our status bar to have the current path info.
84 fileName = new JTextField(50);
86 larch.setSelectionPath(larch.getPathForRow(0));
88 // pop out all the nodes.
91 // Create a panel that uses FlowLayout (the default).
92 JPanel buttonPane = new JPanel();
93 buttonPane.add(fileName);
95 Container contentPane = getContentPane();
96 contentPane.add(listScrollPane, BorderLayout.CENTER);
97 contentPane.add(buttonPane, BorderLayout.NORTH);
100 @SuppressWarnings("unchecked")
101 // given a mutable tree node, this will fetch out the embedded hash table.
102 Hashtable<String, String> NodeToTable(Object node)
104 if (!(node instanceof DefaultMutableTreeNode))
106 Object content = ((DefaultMutableTreeNode) node).getUserObject();
107 if (content != null) {
108 if (content instanceof Hashtable<?, ?>) {
110 return (Hashtable<String, String>) content;
111 } catch (Throwable cause) {
112 logger.error("failed to cast our tree node to a hashtable.");
119 public void valueChanged(TreeSelectionEvent e)
121 fileName.setText("");
122 TreePath sel_path = larch.getSelectionPath();
123 if (sel_path != null) {
124 Hashtable<String, String> table = NodeToTable(sel_path.getLastPathComponent());
126 String name = (String) table.get("name");
127 fileName.setText(name);
132 private static Hashtable<String, String> makeNode(String name, String url, String strPath)
134 Hashtable<String, String> hashtable = new Hashtable<String, String>();
135 hashtable.put("name", name);
136 hashtable.put("url", url);
137 hashtable.put("path", strPath);
141 public class DraggableDroppableTree extends JTree implements IDragonDropDataProvider
143 public DraggableDroppableTree(String startPath)
147 url = new File(startPath).toURI().toURL().toString();
148 } catch (Throwable cause) {
149 logger.warn("failed to calculate URL for " + startPath);
151 setModel(new DefaultTreeModel(new DefaultMutableTreeNode(
152 makeNode("top", url, startPath))));
153 setTransferHandler(new DragonTransferHandler(this));
154 setDragEnabled(true);
158 public boolean consumeDropList(List<Object> fileSet, Point location)
160 logger.debug("into consume dropped files, file set is:");
161 for (int i = 0; i < fileSet.size(); i++) {
162 logger.debug(" " + ((File) fileSet.get(i)).getPath());
168 public List<Object> provideDragList()
170 ArrayList<Object> toReturn = new ArrayList<Object>();
171 TreePath tsp = getSelectionPath();
174 logger.debug("got the path...");
175 Hashtable<String, String> table = NodeToTable(tsp.getLastPathComponent());
177 toReturn.add(new File(table.get("path")));
182 public void expandAll()
185 while (row < getRowCount()) {
193 public class CustomCellRenderer implements TreeCellRenderer
195 DefaultTreeCellRenderer defRend = new DefaultTreeCellRenderer();
197 private String getValueString(Object value)
199 String returnString = "empty";
200 Hashtable<String, String> table = NodeToTable(value);
202 returnString = table.get("name") + " -> " + table.get("url");
204 returnString = "??: " + value.toString();
210 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
211 boolean expanded, boolean leaf, int row, boolean hasFocus)
213 defRend.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
215 defRend.setText(getValueString(value));
220 public static void main(String s[])
222 PropertyConfigurator.configure("log4j.properties");
223 // starting with user's personal area.
224 String homedir = System.getenv("HOME");
225 if ((homedir == null) || (homedir.length() == 0)) {
226 // fall back to the root if no home directory.
229 JFrame frame = new dragdrop_tree_test(homedir);
230 frame.addWindowListener(new WindowAdapter()
232 public void windowClosing(WindowEvent e)
238 frame.setVisible(true);