Dnd in JScrollPane broken in 1.4??

Hello,
I have been trying to enable DnD in an application but have encountered many hurdles, including what appears to be broken DnD support for components within scroll panes. I've filed a bug report in Sun's database, but was hoping perhaps someone else has encountered this problem before.
The problem arises when the user performs a DnD operation, and drags an object over a scroll pane. This example program demonstrates the bug. Select a row in the table, then drag it over the empty portion of the scroll pane. You should see a stack trace thrown to the console.
Has anybody encountered this bug before, and if so, are there any known workarounds?
- Aaron
public class ViewportTransferHandlerDemo implements Runnable {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new ViewportTransferHandlerDemo());
  public void run() {
    JTable table = new JTable();
    table.setModel(new DefaultTableModel(new String[][] { { "Apple" }, { "Banana" }, { "Cherry" } }, new String[] { "Fruits" }));
    table.setDragEnabled(true);
    table.setTransferHandler(new TransferHandler() {
      protected Transferable createTransferable(JComponent c) {
        JTable t = (JTable) c;
        return new StringSelection((String) t.getValueAt(t.getSelectedRow(), 0));
      public boolean importData(JComponent comp, Transferable t) {
        JTable table = (JTable) comp;
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        try {
          model.setValueAt(t.getTransferData(DataFlavor.stringFlavor), Math.max(0, table.getSelectedRow()), 0);
          return true;
        } catch (UnsupportedFlavorException e) {
          throw new RuntimeException(e);
        } catch (IOException e) {
          throw new RuntimeException(e);
      public int getSourceActions(JComponent c) {
        return COPY_OR_MOVE;
      public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
        return true;
    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new BorderLayout());
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(table);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    SwingUtilities.updateComponentTreeUI(frame);
    frame.pack();
    frame.show();
}

I always return true to keep the example super-simple.
The transferhandler is only assigned to the table. The table serves as both the drag source and the drop target. If you play with this example, you can drag from one row in the table to another row in the table, and it works O.K.
If i were concerned about making the example more robust, I would probably do some type checking in the canImport method, but for this example I just wanted to keep the line count down.

Similar Messages

  • JTable DND requires two clicks (fixed but broken in 1.6)

    I'm using a JTable as a source of a drag and drop operation.
    I can easily get it to work, however, when I want to start a drag from an unselected row I have to first click on the row to select it and then mouse-down on the row and then I can drag it.
    I found a workaround and it was working flawlessly. I was caching the mouse-down and technically firing it twice. Although it seemed like a really cheap trick it worked, but now in 1.6 it doesn't.
    Any ideas?

    Alright, here's the code. I've tried a bunch of things, but if you can get a single-click drag working on this example, then it'll work in my stuff as well.
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class JTableDNDExample extends JTable
      // the data for the table...
      private String[][] data =
          { "Cell 1-1", "Cell 2-1", "Cell 3-1" },
          { "Cell 1-2", "Cell 2-2", "Cell 3-2" },
          { "Cell 1-3", "Cell 2-3", "Cell 3-3" },
          { "Cell 1-4", "Cell 2-4", "Cell 3-4" },
          { "Cell 1-5", "Cell 2-5", "Cell 3-5" },
      // the columns for the table...
      private String[] columns = { "Column 1", "Column 2", "Column 3" };
      public JTableDNDExample()
        // enable the drag...
        this.setDragEnabled(true);
        // create the table model with the default data...
        DefaultTableModel model = new DefaultTableModel(data, columns);
        this.setModel(model);
        // get the selection model...
        ListSelectionModel selectionModel = this.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // set the selection possibilities...
        this.setCellSelectionEnabled(false);
        this.setRowSelectionAllowed(true);
        this.setColumnSelectionAllowed(false);
        // create the trasnfer handler for the table...
        TransferHandler th = new TransferHandler()
          public int getSourceActions(JComponent comp)
            // return the copy or move action...
            return DnDConstants.ACTION_COPY_OR_MOVE;
          protected Transferable createTransferable(JComponent comp)
               int index = getSelectedRow();
               if(index >= 0 && index < data.length)
                 // get the value at the index...
                 String value = data[index][0];
                 // get the string transferable for the string...
                 StringSelection transferable = new StringSelection(value);
                 // return the rtansferable...
              return transferable;
            // no element to transfer, return null...
            return null;
          public boolean canImport(JComponent comp, DataFlavor[] flavors)
            // cannot import, return false...
            return false;
        // se tthe transfer handler...
        this.setTransferHandler(th);
      public static void main(String[] args)
        JFrame frame = new JFrame("JTable DND Example");
        frame.getContentPane().setLayout(new GridBagLayout());
        JTableDNDExample table = new JTableDNDExample();
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0,
          GridBagConstraints.CENTER, GridBagConstraints.BOTH,
          new Insets(6, 6, 6, 6), 0, 0));
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

  • DnD icon won't go away on Redhat 9

    Background:
    I recently updated my OS to RedHat 9 (2.4.20-6). Previously on Redhat 7.3 (kernel upgraded to 2.4.18ish) everything worked OK.
    java -version
    java version "1.4.1-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1-beta-b14)
    Java HotSpot(TM) Client VM (build 1.4.1-beta-b14, mixed mode)
    Problem:
    After dragging and dropping an object the drag icon/cursor turns black/reverse-video and does not go away until I drag another object or move the icon/cursor out of the window. The problem did not occur before my upgrade so I imaging it is not a java problem. I would like to know if anyone can repeat the problem or if anyone else has seen it. One Caveate... if you do anything after the drop that causes an icon repaint (like the OptionPane that is commented out in the code below) the problem does not appear. I have not been able to reproduce the problem outside of java.
    thanks
    Brad
    Example:
    This code by Gupta is a simple example to demonstrate the problem.
    file DNDComponentInterface.java
    <code>
    public interface DNDComponentInterface{
    public void addElement( Object s);
    public void removeElement();
    </code>
    file DNDList.java
    <code>
    /**his is an example of a component, which serves as a DragSource as
    * well as Drop Target.
    * To illustrate the concept, JList has been used as a droppable target
    * and a draggable source.
    * Any component can be used instead of a JList.
    * The code also contains debugging messages which can be used for
    * diagnostics and understanding the flow of events.
    * @version 1.0
    import java.awt.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    import java.util.Hashtable;
    import java.util.List;
    import java.util.Iterator;
    import java.io.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.JList;
    import javax.swing.DefaultListModel;
    public class DNDList extends JList
    implements DNDComponentInterface, DropTargetListener,DragSourceListener, DragGestureListener {
    * enables this component to be a dropTarget
    DropTarget dropTarget = null;
    * enables this component to be a Drag Source
    DragSource dragSource = null;
    * constructor - initializes the DropTarget and DragSource.
    public DNDList() {
    dropTarget = new DropTarget (this, this);
    dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_MOVE, this);
    * is invoked when you are dragging over the DropSite
    public void dragEnter (DropTargetDragEvent event) {
    // debug messages for diagnostics
    System.out.println( "dragEnter");
    event.acceptDrag (DnDConstants.ACTION_MOVE);
    * is invoked when you are exit the DropSite without dropping
    public void dragExit (DropTargetEvent event) {
    System.out.println( "dragExit");
    * is invoked when a drag operation is going on
    public void dragOver (DropTargetDragEvent event) {
    System.out.println( "dragOver");
    * a drop has occurred
    public void drop (DropTargetDropEvent event) {
    try {
    Transferable transferable = event.getTransferable();
    // we accept only Strings
    if (transferable.isDataFlavorSupported (DataFlavor.stringFlavor)){
    // KBS
    //event.acceptDrop(DnDConstants.ACTION_MOVE);
    //event.getDropTargetContext().dropComplete(true);
    // KBS
    // KBS Added this
    /* You must leave this commented out to replicate the DND icon ghost problem
    int answer = JOptionPane.showConfirmDialog(this,
    "Are you sure?",
    "Warning",
    JOptionPane.YES_NO_OPTION);
    int answer = JOptionPane.YES_OPTION;
    if (answer == JOptionPane.YES_OPTION)
    // KBS To here
    event.acceptDrop(DnDConstants.ACTION_MOVE);
    String s = (String)transferable.getTransferData ( DataFlavor.stringFlavor);
    addElement( s );
    event.getDropTargetContext().dropComplete(true);
    // KBS Added this
    // KBS To here
    else{
    event.rejectDrop();
    catch (IOException exception) {
    exception.printStackTrace();
    System.err.println( "Exception" + exception.getMessage());
    event.rejectDrop();
    catch (UnsupportedFlavorException ufException ) {
    ufException.printStackTrace();
    System.err.println( "Exception" + ufException.getMessage());
    event.rejectDrop();
    * is invoked if the use modifies the current drop gesture
    public void dropActionChanged ( DropTargetDragEvent event ) {
    * a drag gesture has been initiated
    public void dragGestureRecognized( DragGestureEvent event) {
    Object selected = getSelectedValue();
    if ( selected != null ){
    StringSelection text = new StringSelection( selected.toString());
    // as the name suggests, starts the dragging
    dragSource.startDrag (event, DragSource.DefaultMoveDrop, text, this);
    } else {
    System.out.println( "nothing was selected");
    * this message goes to DragSourceListener, informing it that the dragging
    * has ended
    public void dragDropEnd (DragSourceDropEvent event) {  
    if ( event.getDropSuccess()){
    removeElement();
    * this message goes to DragSourceListener, informing it that the dragging
    * has entered the DropSite
    public void dragEnter (DragSourceDragEvent event) {
    System.out.println( " dragEnter");
    * this message goes to DragSourceListener, informing it that the dragging
    * has exited the DropSite
    public void dragExit (DragSourceEvent event) {
    System.out.println( "dragExit");
    * this message goes to DragSourceListener, informing it that the dragging is currently
    * ocurring over the DropSite
    public void dragOver (DragSourceDragEvent event) {
    System.out.println( "dragExit");
    * is invoked when the user changes the dropAction
    public void dropActionChanged ( DragSourceDragEvent event) {
    System.out.println( "dropActionChanged");
    * adds elements to itself
    public void addElement( Object s ){
    (( DefaultListModel )getModel()).addElement (s.toString());
    * removes an element from itself
    public void removeElement(){
    (( DefaultListModel)getModel()).removeElement( getSelectedValue());
    </code>
    file TestDND.java
    <code.
    * The tester class for the DNDList. This class creates the lists,
    * positions them in a frame, populates the list with the default
    * data.
    * @version 1.0
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestDND
    public static void main (String args[]) {
    TestDND testDND = new TestDND();
    * constructor
    * creates the frame, the lists in it and sets the data in the lists
    public TestDND()
    JFrame f = new JFrame("Drag and Drop Lists");
    DNDList sourceList = new DNDList();
    // add data to the source List
    DefaultListModel sourceModel = new DefaultListModel();
    sourceModel.addElement( "Source Item1");
    sourceModel.addElement( "Source Item2");
    sourceModel.addElement( "Source Item3");
    sourceModel.addElement( "Source Item4");
    // gets the panel with the List and a heading for the List
    JPanel sourcePanel = getListPanel(sourceList, "SourceList", sourceModel);
    DNDList targetList = new DNDList();
    // add data to the target List
    DefaultListModel targetModel = new DefaultListModel();
    targetModel.addElement( "Target Item1");
    targetModel.addElement( "Target Item2");
    targetModel.addElement( "Target Item3");
    targetModel.addElement( "Target Item4");
    JPanel targetPanel = getListPanel(targetList, "TargetList", targetModel);
    JPanel mainPanel = new JPanel();
         mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
    mainPanel.add( sourcePanel );
    mainPanel.add( targetPanel );
    f.getContentPane().add( mainPanel );
    f.setSize (300, 300);
    f.addWindowListener (new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    f.setVisible (true);
    * a convenience method
    * used for positioning of the ListBox and the Label.
    * @param list - the special DND List
    * @param labelName - the heading for the list
    * @param listModel - model for the list
    private JPanel getListPanel(DNDList list, String labelName, DefaultListModel listModel ){ 
    JPanel listPanel = new JPanel();
    JScrollPane scrollPane = new JScrollPane(list);
    list.setModel(listModel);
    JLabel nameListName = new JLabel(labelName );
    listPanel.setLayout( new BorderLayout());
    listPanel.add(nameListName, BorderLayout.NORTH);
    listPanel.add( scrollPane, BorderLayout.CENTER);
    return listPanel;
    </code>

    HI,
    Try Resetting your iPhone
    Carolyn

  • DnD with 2D scaled drop target

    This is more a strategy question than a code question - although code examples will be muchly appreciated.
    I have a model drawing component (ModelDrawingComponent extends JInternalFrame) that contains child components ( ie. ClassNode extends JInternalFrame). I need to be able to drop information into the child component (ClassNode). My description is greatly simplified leaving out several layers such as JScrollPanes, JPanels, etc.
    I have overridden the main JPanel's paintComponent() method to allow 2D drawing of lines and scale transformations of the entire model component resultant view. To provide mouse event interactions for this I use a GlassPane which transforms the mouse point to a scaled component adjusted point.
    My problem is implementing a DropTarget for Drag and Drop with 2D scaling - the mouse gestures reference points that are not adjusted for the scaling. So I need to transform the point geometry to determine whether the drag is over one of the ClassNode components.
    Does anyone have experience with DnD and 2D transformed targets they would like to share - ie. what is the best strategy for managing the transformation of the current drag point to the transformed / scaled point? I am assuming that the DropTarget should be the GlassPane. If so, how do you manage only showing a Drop OK Cursor when the cursor is over a child (ie. ClassNode) instead of over the GlassPane? What event listeners do I need to override to accomplish this?
    Thanks in advance.

    I don't know why your DropTarget implementation doesn't work, but an alternative, more high-level way of doing what you want is to use a TransferHandler:
            canvas.setTransferHandler(new TransferHandler() {
                @Override
                public boolean canImport(TransferSupport support) {
                    if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                        support.setDropAction(DnDConstants.ACTION_COPY);
                        return true;
                    return false;
                @Override
                public boolean importData(TransferSupport support) {
                    try {
                        String text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                        System.out.println(text);
                        return true;
                    catch (Exception ex) {
                        ex.printStackTrace();
                        return false;
            });

  • Problem about using JTextPane in JScrollPane

    I put a JTextPane in a JScrollPane.
    But when I reduce the window size of the JScrollPane with my mouse, the text line in the JTextPane is broken to newlines automatically due to the reduced window size.
    How to prevent the text lines breaking in this situation!

    OK, so the words are wrapping when they're not suppose to. How are you adding your JTextPane to the JScrollpane? Also, does setting a preferred size or a minimum size on the JTextPane help?
    That's an odd problem. In looking at the API I see that JTextArea and JTextPane are both derived (eventually) from JTextComponent. But the line wrap option is only in JTextArea. This makes me think that it would be possible to overload paint method of the JTextPane. But wow! That would be messy.
    I'll keep thinking about it. Let us know if you find a solution.

  • Multiple DnD in JTreeTable

    Hi Folks--
    two weeks ago I started to implement Drag and Drop for my wonderful TreeTableComponent, that is based on a JTreeTable described in an article by sun. It didn't took me long to figure that dnd is not the easiest thing to do for a JTreeTable. So I browsed this forum and found many other people who have or had the same problem. Since the given answers didn't help me so much, I thought it would be good to publish my implementation here:
    After two weeks I managed to implement dnd in the right way (as I belive). Here's my solution.
    1. disable internal dnd function by setDragEnabled(false)
    2. set your own transfer handler that manages dnd for you (derive from TransferHander or simply create an instance of TransferHandler)
    3. add a mouse listener and a mouse motion listener to your treeTable to tell the transfer handler to start the drag
    4. revert order of mouse listener that you mouse listener is called first -> this is importent to keep selection on all previously selected nodes (prevents internal mouse handler of tree changing selection to the node you just clicked onto)
    5. set selection mode of table and tree to make multiple selection possible to the user
    add this where you init the table:
    ('table' is instance of a JTreeTable derivative)
            //disable internal dnd functionality, because we need our own implementation
            table.setDragEnabled(false); 
           //attach transfer handler
            table.setTransferHandler(createTransferHandler());
            //since we have a transfer handler, we just need to attach mouse listeners
            //to initiate the drag inside of the transfer handler
            DnDMouseAdapter dndMouseAdapter = new DnDMouseAdapter();
            table.addMouseListener(dndMouseAdapter);
            table.addMouseMotionListener(new DnDMouseMotionAdapter());
            //revert MouseListeners order so that our MouseListener is called first
            //this is important to give drag n drop first priority and prevent the
            //internal mouse handler of tableUI changing the selection.
            MouseListener[] mls = table.getMouseListeners();
            for (int i = 0; i < mls.length; i++) {
                if (mls[i] != dndMouseAdapter) {
                    table.removeMouseListener(mls);
    table.addMouseListener(mls[i]);
    //set multiple selection
    table.getSelectionModel().setSelectionMode(getSelectionMode());
    //set selection mode for tree
    final JTree tree = getTreeTable().getTree();
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    The idea for the mouse listeners I got from sun's swing tutorial. So here's the code for dndMouseAdapter and dndMouseMotionAdapter:
      class DnDMouseAdapter extends MouseAdapter {
            public void mousePressed(MouseEvent e) {
                firstMouseEvent = e;
                e.consume();
            public void mouseReleased(MouseEvent e) {
                firstMouseEvent = null;
        class DnDMouseMotionAdapter extends MouseMotionAdapter {
            //define diplacement of five pixel for as drag
            private static final int PIXEL_DISPLACEMENT = 5;
            public void mouseDragged(MouseEvent e) {
                if (firstMouseEvent != null) {
                    e.consume();
                    //if the user holds down the control key -> COPY, otherwise MOVE
                    int ctrlMask = InputEvent.CTRL_DOWN_MASK;
                    int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask) ? TransferHandler.COPY : TransferHandler.MOVE;
                    int dx = Math.abs(e.getX() - firstMouseEvent.getX());
                    int dy = Math.abs(e.getY() - firstMouseEvent.getY());
                    //define a displacement of at least some pixel as a drag
                    if (dx > DnDMouseMotionAdapter.PIXEL_DISPLACEMENT || dy > DnDMouseMotionAdapter.PIXEL_DISPLACEMENT) {
                        //starting to drag...
                        JComponent c = (JComponent) e.getSource();
                        TransferHandler handler = c.getTransferHandler();
                        //tell transfer handler to start drag
                        handler.exportAsDrag(c, firstMouseEvent, action);
                        //reset first mouse event for the next time
                        firstMouseEvent = null;
        }I hope that helps! ;-)
    Any comment is apprechiated!
    Kind regards,
    Patrick

    I'm absolutetly devastated!!
    I spent hours looking for advice on a treetable component after someone mentioned the idea not too long ago, in another thread might I add.
    And I just spent the last 2 damn weeks implementing myy own. I feel heart broken! JTreeTable v1 was even very similar tomy first bash...but I gave on using the JTree as the renderer as it just looked lame... the way I did it anyway.
    So just today I finished my own impl, with a new JComponent derivative soley for the rendering of the tree-like column.
    Any clue as to when they intend to make it a standard JFC Swing component.
    Bloody marvelous! So annoyed as it was a serious road-block to my current project! And asmuch as it was fun, I didn't choose to do for fun. AAAAAAARRRGGH!!
    ps. congratulations, if you feel at all like how I felt half an hour ago, you must be very chuffed.

  • Autoscroll behavior during DnD in JTree, 1.4 vs 1.6

    The following code compiles under both Java 1.4 and Java 1.6. I'm wondering if anyone knows why the following actions cause different behaviors between the two versions:
    1. When the frame opens, you should see a fully-expanded tree (which, because of the small size, causes a vertical scrollbar to appear).
    2. Make a drag-and-drop gesture on the first child node ("blue"), and attempt to cause the tree to scroll down so you can drop it on the last parent node ("food").
    Under 1.6, the tree scrolls nicely as you hold the DnD gesture.
    Under 1.4, the tree does not scroll. I had some hope JTree.setAutoscrolls(true) would help, but it did not.
    Any suggestions how to get 1.4 to behave the way 1.6 does?
    Thanks for your time.
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import java.util.Enumeration;
    public class AutoScroll14 extends JFrame {
        public static void main(String[] args) {
            new AutoScroll14();
        public AutoScroll14() throws HeadlessException {
            super("AutoScroll 1.4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            public boolean importData(JComponent comp, Transferable t) {
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return false;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return false;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return true;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    return new StringTransferable(toTransfer);
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { localStringFlavor };
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;

    I added the class "TreeDropTarget".
    "TreeDropTarget" extends the class "DropTarget", which implements the interface "DropTargetListener".
    DropTargetListener has a few methods, that are called automatically by Swing during drag operation
    (dragOver, dragExit, drop). So we can implement "autoscroll", as well as "automatic node expansion".
    With "automatic node expansion", a collapsed node will be expanded,
    so that its children become visible and we can do a drop on them:
    package demo;
    * AutoScroll.java
    * source level 1.4
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.io.*;
    import java.util.*;
    public class AutoScroll extends JFrame {
        public static void main(String[] args) {
            new AutoScroll();
        public AutoScroll() throws HeadlessException {
            super("AutoScroll " + System.getProperty("java.version"));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            tree.setDropTarget(new TreeDropTarget());//<----------------------
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private AutoScroll.MyTransferHandler.StringTransferable transferable;
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            protected void exportDone(JComponent comp, Transferable t, int action) {
                if (t == null) {
                    t = transferable;
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    transferable = new StringTransferable(toTransfer);
    return transferable;
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[]{localStringFlavor};
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;
    class TreeDropTarget extends DropTarget {
    public TreeDropTarget() {
    super();
    public void dragOver(DropTargetDragEvent dtde) {
    JTree tree = (JTree) dtde.getDropTargetContext().getComponent();
    Point loc = dtde.getLocation();
    updateDragMark(tree, loc);
    autoscroll(tree, loc);
    super.dragOver(dtde);
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTree tree, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = tree.getVisibleRect();
    Rectangle inner = new Rectangle(
    outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(
    cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    tree.scrollRectToVisible(scrollRect);
    public void updateDragMark(JTree tree, Point location) {
    int row = tree.getRowForPath(tree.getClosestPathForLocation(location.x, location.y));
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
    markNode(tree, location);
    private void markNode(JTree tree, Point location) {
    TreePath path = tree.getClosestPathForLocation(location.x, location.y);
    if (path != null) {
    if (lastRowBounds != null) {
    Graphics g = tree.getGraphics();
    g.setColor(Color.white);
    g.drawLine(lastRowBounds.x, lastRowBounds.y,
    lastRowBounds.x + lastRowBounds.width, lastRowBounds.y);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    private Rectangle lastRowBounds;
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);

  • Drag/drop into JTable inside JScrollPane

    Hello,
    I have a table inside a JScrollPane. I can set the table as the DropTarget by the command:
    new DropTarget(table,fileDropTargetListener);
    but I cannot set the JScrollPane be the DropTarget by the same command.
    the problem is that: I cannot set the table to fit the JScrollPane by the command setsize(scrollPane.getSize() ), setPreferedSize(scrollPane.getPreferedSize()), (don't know for what reason, they don't work to fit the scrollpane), therefore when user drags an item to the JScrollPane but outside the table, the drag gesture doesnot display.
    Please anyone help me how to solve this problem. Thank you,
    fantabk

    Yes, I use custom cell renderer and cell editor for ParentTable, which returns NestedTable.
    DnD turned on for the ParentTable, so when the NestedTable is active (some cells selected in it) it receives DnD events, which are turned off for it, and DnD doesn't work.
    Possible solution is to turn DnD for NestedTable (not for ParentTable), and i'll do this if it is impossible to make it work in current configuration.
    So the question is � is this possible do not pass DnD event to NestedTable ?

  • Jackd + guitar: "timeouts and broken pipes"

    Hi friends! I'm trying to pass my electric guitar via any rack/effects (like Guitarix or Creox) with no luck. I've got this sound card:
    01:06.0 Multimedia audio controller: Creative Labs [SB Live! Value] EMU10k1X
    01:06.1 Input device controller: Creative Labs [SB Live! Value] Input device controller
    I try with QJackCtl and invoking jackd from the terminal with any luck.
    jackd -d alsa -C -P
    jackd 0.121.3
    Copyright 2001-2009 Paul Davis, Stephane Letz, Jack O'Quinn, Torben Hohn and others.
    jackd comes with ABSOLUTELY NO WARRANTY
    This is free software, and you are welcome to redistribute it
    under certain conditions; see the file COPYING for details
    could not open driver .so '/usr/lib/jack/jack_net.so': libcelt0.so.2: cannot open shared object file: No such file or directory
    could not open driver .so '/usr/lib/jack/jack_firewire.so': libffado.so.2: cannot open shared object file: No such file or directory
    JACK compiled with System V SHM support.
    loading driver ..
    creating alsa driver ... hw:0|hw:0|1024|2|48000|0|0|nomon|swmeter|-|32bit
    control device hw:0
    configuring for 48000Hz, period = 1024 frames (21.3 ms), buffer = 2 periods
    ALSA: final selected sample format for capture: 16bit little-endian
    ALSA: use 2 periods for capture
    ALSA: final selected sample format for playback: 16bit little-endian
    ALSA: use 2 periods for playback
    jackd watchdog: timeout - killing jackd
    [gabo@machina ~]$
    This is the output from QJackCtl:
    00:12:07.126 Client deactivated.
    00:12:07.130 JACK is being forced...
    cannot read server event (Success)
    cannot continue execution of the processing graph (Bad file descriptor)
    zombified - calling shutdown handler
    cannot send request type 7 to server
    cannot read result for request type 7 from server (Broken pipe)
    cannot send request type 7 to server
    cannot read result for request type 7 from server (Broken pipe)
    00:12:07.339 JACK was stopped with exit status=1.
    I can hear my guitar and record with Audacity, but when jackd enter into the escenario everything blows up. I read that nowadays almost any sound card will work with QJackCtl with the default options. I play with the parameters and sometimes jack refuse to start. With the default options on i can make it run, but i get no sound of the racks or guitar effects processors neither the guitar tuners that use jack takes the sound from the guitar. My line input is in capture via alsamixer, but still no luck. Any clue on this? I'm skipping steps?
    Thanks in advance.
    iamgabo

    Hi!
    groups && cat /proc/asound/cards && cat ~/.asoundrc && cat '/etc/security/limits.d/audio.conf' && jackd -v
    adm disk lp wheel http network video audio optical storage power users polkitd vboxusers wireshark kismet
    0 [Live ]: EMU10K1X - Dell Sound Blaster Live!
    Dell Sound Blaster Live! at 0xcc00 irq 17
    #pcm.upmix71 {
    #type upmix
    #slave.pcm "surround71"
    #delay 15
    #channels 8
    pcm.!default {
    type hw
    card 0
    ctl.!default {
    type hw
    card 0
    # convert alsa API over jack API
    # use it with
    # % aplay foo.wav
    # use this as default
    pcm.!default {
    type plug
    slave { pcm "jack" }
    ctl.mixer0 {
    type hw
    card 1
    # pcm type jack
    pcm.jack {
    type jack
    playback_ports {
    0 system:playback_1
    1 system:playback_2
    capture_ports {
    0 system:capture_1
    1 system:capture_2
    cat: /etc/security/limits.d/audio.conf: No such file or directory
    I have a file called 99-audio.conf
    cat /etc/security/limits.d/99-audio.conf
    @audio - rtprio 99
    @audio - memlock unlimited
    Also i've seen some guys changing this file too:
    cat /etc/security/limits.conf
    # /etc/security/limits.conf
    #Each line describes a limit for a user in the form:
    #<domain> <type> <item> <value>
    #Where:
    #<domain> can be:
    # - an user name
    # - a group name, with @group syntax
    # - the wildcard *, for default entry
    # - the wildcard %, can be also used with %group syntax,
    # for maxlogin limit
    #<type> can have the two values:
    # - "soft" for enforcing the soft limits
    # - "hard" for enforcing hard limits
    #<item> can be one of the following:
    # - core - limits the core file size (KB)
    # - data - max data size (KB)
    # - fsize - maximum filesize (KB)
    # - memlock - max locked-in-memory address space (KB)
    # - nofile - max number of open files
    # - rss - max resident set size (KB)
    # - stack - max stack size (KB)
    # - cpu - max CPU time (MIN)
    # - nproc - max number of processes
    # - as - address space limit (KB)
    # - maxlogins - max number of logins for this user
    # - maxsyslogins - max number of logins on the system
    # - priority - the priority to run user process with
    # - locks - max number of file locks the user can hold
    # - sigpending - max number of pending signals
    # - msgqueue - max memory used by POSIX message queues (bytes)
    # - nice - max nice priority allowed to raise to values: [-20, 19]
    # - rtprio - max realtime priority
    #<domain> <type> <item> <value>
    #* soft core 0
    #* hard rss 10000
    #@student hard nproc 20
    #@faculty soft nproc 20
    #@faculty hard nproc 50
    #ftp hard nproc 0
    #@student - maxlogins 4
    * - rtprio 0
    * - nice 0
    @audio - rtprio 65
    @audio - nice -10
    @audio - memlock unlimited
    jackd 0.121.3
    There are the snaps for QJackCtl
    Also, checkout this stuff that i've recorded with audacity, only from the line and nothing else
    http://ompldr.org/vZ3A2eg
    Thanks!
    Last edited by iamgabo (2012-12-15 02:21:08)

  • HT1688 I have a damaged I-Phone and I need the contents of my calendar off of it. I did not have Mobile me at the time.  Can I swap out the sim card from the broken phone to a new phone and recover this calendar?

    I have an older I-Phone (3G) that for some reason the body of the phone has split in two.  This phone was a business phone and it had a lot of important information on it. I have a second phone that is also a 3G.  On the broken phone there is a lot of important information that I need in my calendar. Im not worried about anything else but the calendar.  I didn't have the Mobile Me account at that time or I would be having this problem. Does anybody know if I can ust switch out the sim cards. I just need to recover the old calendar, so im hoping that the calendar will transfer when I switch the sim card into the good 3G. If that doesn't work does anybody know of anyway that I can retrieve this information off of this phone?

    Nothing is stored on the sim card on an iPhone.  If you backed up to your computer the backup will contain your calendar events.  Otherwise, if your phone isn't functioning there is no way to back up or extract your calendar at this point.

  • HT1384 My lock screen/power button on my iPod Touch is broken, and I need some assistance.

    As the title suggests, I can not use the lock screen/power button on my iPod Touch, it is broken. I can use Adaptive Touch to turn the screen on and off at will, and also turn my device off. But if I turn it off, I don't know how to get it to turn back on. Could I just plug it into a charger and turn it back on, or would I need to plug it into my computer? Please help, in a few days I won't have access to it for 9 weeks, I need immediate help.

    If you power off the iPod, it will turn back on if you connect it to a charger like a wall charger or a computer. I just checked with a charging source to confirm. I knew it did it with a computer.

  • Error during 10.8.2 Update - Appstore and iTunes Broken

    Hi Guys,
    I hope you can help me with this one.
    I just installed the 10.8.2 update trough App Store, then it asked me to restart my computer... During the restart some error message appeared saying that the installation could not be completed due to an unexpected error, and then restarted my computer automatically.
    The problem is, now both my App Store and iTunes are broken, here are the details of the error message I get when I try to launch App Store either normally or using the Apple > Software Update menu option:
    Process:         App Store [419]
    Path:            /Applications/App Store.app/Contents/MacOS/App Store
    Identifier:      com.apple.appstore
    Version:         1.2.1 (129.7)
    Build Info:      Firenze-129007000000000~2
    Code Type:       X86-64 (Native)
    Parent Process:  launchd [157]
    User ID:         501
    Date/Time:       2012-09-20 15:09:21.308 -0300
    OS Version:      Mac OS X 10.8.1 (12B19)
    Report Version:  10
    Interval Since Last Report:          1063564 sec
    Crashes Since Last Report:           1
    Per-App Crashes Since Last Report:   8
    Anonymous UUID:                      877BB7B8-8322-4C71-BEFF-67D640D02852
    Crashed Thread:  0
    Exception Type:  EXC_BREAKPOINT (SIGTRAP)
    Exception Codes: 0x0000000000000002, 0x0000000000000000
    Application Specific Information:
    dyld: launch, loading dependent libraries
    Dyld Error Message:
      Library not loaded: /System/Library/PrivateFrameworks/CoreRecognition.framework/Versions/A/CoreReco gnition
      Referenced from: /Applications/App Store.app/Contents/MacOS/App Store
      Reason: image not found
    Binary Images:
           0x107a22000 -        0x107aa2fff  com.apple.appstore (1.2.1 - 129.7) <31AAF1C2-2BE9-393B-ABFD-6D869F72E909> /Applications/App Store.app/Contents/MacOS/App Store
        0x7fff67622000 -     0x7fff6765693f  dyld (210.2.3) <A40597AA-5529-3337-8C09-D8A014EB1578> /usr/lib/dyld
    Model: MacBook6,1, BootROM MB61.00C8.B00, 2 processors, Intel Core 2 Duo, 2.26 GHz, 8 GB, SMC 1.51f53
    Graphics: NVIDIA GeForce 9400M, NVIDIA GeForce 9400M, PCI, 256 MB
    Memory Module: BANK 0/DIMM0, 4 GB, DDR3, 1067 MHz, 0x0198, 0x393930353432382D3032302E4130304C4620
    Memory Module: BANK 1/DIMM0, 4 GB, DDR3, 1067 MHz, 0x0198, 0x393930353432382D3032302E4130304C4620
    AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x93), Broadcom BCM43xx 1.0 (5.106.98.81.21)
    Bluetooth: Version 4.0.9f8 10405, 2 service, 18 devices, 1 incoming serial ports
    Network Service: AirPort, AirPort, en1
    Serial ATA Device: KINGSTON SV100S264G, 64,02 GB
    Serial ATA Device: Hitachi HTS545025B9SA02, 250,06 GB
    USB Device: Samsung S2 Portable, 0x04e8  (Samsung Electronics Co., Ltd.), 0x1f05, 0x24100000 / 3
    USB Device: Built-in iSight, apple_vendor_id, 0x8507, 0x24400000 / 2
    USB Device: BRCM2070 Hub, 0x0a5c  (Broadcom Corp.), 0x4500, 0x06100000 / 2
    USB Device: Bluetooth USB Host Controller, apple_vendor_id, 0x8218, 0x06130000 / 5
    USB Device: Apple Internal Keyboard / Trackpad, apple_vendor_id, 0x0236, 0x04600000 / 2
    I appreciate if you could help me,
    Best Regards,
    Dante Araujo

    I had this problem too.
    Go to http://support.apple.com/kb/DL1580
    Download the update manually and install. Worked on my MBP15 retina.
    Regards
    Chris

  • How do i transfer my musiclibrary from my iphone to a new computer since the computer the iphone is synct with is broken and no longer works

    if the computer your music library is synct with  is broken how do y transfer your music on your iphone to a new itunes on a new computer

    1. Disable automatic syncing on connection:  iTunes Prefs > Devices > Disable....
    2. Connect phone.
    3. Right-click the device tab on left border of iTunes window and select "Transfer Purchases."  This will transfer all iTunes store purchased music, media and apps to the iTunes library on the computer. 
    It won't transfer non-iTunes store music/media (i.e. CD's you ripped  yourself) and these will get deleted from the phone when you sync.  There are 3rd party apps for your computer which may be able to backup non-iTunes media on your phone.  Google.

  • [LaserJet Pro 200 color MFP M276nw] only vertical lines when scanning, scanner broken?

    Hi all! I have a problem with the scanner in my HP all in one. If I scan (using the printer function or apples ImageCapture: same result) the output is just a lot of vertical stripes (in colors when in color mode). Not a trace of the image I try to scan. The lines are there even if i scan an empty white page. I see the stripes both when doing a preview scan and an actual scan. The problems are very similar regardless of if I use the flatbed or the feeder scanner (they are separate scanner hardware, yes?). I have updated to the latest software for the printer/scanner and I am connecting over bonjour via wireless. I am on Os X 10.9.1. Anybody having similar problems or is my scanner just plain broken? Thanks in advance!Jon

    , , I understand that both of you are seeing vertical lines when scanning from your Laserjet M276nw. First, make sure the printer is plugged directly into a wall outlet and not a surge protector. Now, so I know where to begin I'd need to know the following:If you are seeing the vertical lines when you copy as well as scan?Are you seeing the vertical lines when you copy from the flatbed? The document feeder? both?If you are seeing the lines from both the flatbed and the feeder are they in the same place?Once I know this I'll be better able to assist you.

  • My Mac has broken and I want to sell it for parts. How can I be sure that my personal data that is/was on the hard drive is safe?

    My 2006 MacBook Pro has broken. There is a little bit of drive noise when I turn it on, but then nothing happens. It is no big deal. Most of my files were backed up. There are a few files I would like to recover if possible, but nothing worth a major effort.
    I have seen that broken MacBook Pro's go for about $300 on eBay for parts, so I would like to sell the MacBook Pro. However, I only want to do that after I am sure that my personal data is wiped out. Does anyone know how I can accomplish that? Does anyone know of an easy way to search the old hard drive for some of the data that I lost? Can a Genius Bar take care of this stuff for me (and how much do they charge?)?
    Thank you for your help.
    - Eric

    EricNY wrote:
    I only want to do that after I am sure that my personal data is wiped out. Does anyone know how I can accomplish that?
    The ONLY real secure way to be sure that noone may recover data from your drive is, to remove the drive, and drill one or two 1" holes thru the disk.
    A bit less secure but useful way is, to wipe out the data with a tool that's overwrite all sectors of the drive with randomized data in multiple runs.
    For example: Permanent Ereaser http://www.edenwaith.com/products/permanent%20eraser/
    Independent tests bring out, that even specialized recovery companies with forensic tools are unable to find useful data after such a run.
    EricNY wrote:
    Does anyone know of an easy way to search the old hard drive for some of the data that I lost?
    There are some recovery tools out there to fit your needs, e.g. MacKeeper http://mackeeper.zeobit.com/mac-data-recovery
    Lupunus

Maybe you are looking for

  • Win 8.1 Lock Up After 5 min, "Memory Management" or "Cache Error"

    Systems blue screens every few minutes. MS offered a variety of error messages, now is uniformly "Memory Mangement". Chrome shows a Cache Error. Any ideas?

  • Safari Keeps Crashing on MacBook Pro 10.9.1

    Can someone who knows what to look for take a peek and see what's up here? Here is the crash report: Process:     Safari [3178] Path:        /Applications/Safari.app/Contents/MacOS/Safari Identifier:  com.apple.Safari Version:     7.0.1 (9537.73.11)

  • How to activate a an unlocked iphone 5 without a sim card?

    Hi, I just got an unlocked Iphone 5 and I want to activate it but I don't have a sim card, Can I till do it? Thanks to all. 

  • GL drilldown to INV

    i am trying to reconcile INV with GL with the below query....am i missing sthg in the query..i am not able to match the amounts b/w INV to GL. SELECT MTA.BASE_TRANSACTION_VALue from gl_je_headers GJH , gl_import_references GIR , gl_je_lines GJL , gl_

  • Problem in SG300 POE 28 port

    Dear i have problem in Poe port i have Access point TP link tl-wa5110g High Power when i bluged in switch i can`t take power from switch note Acess point support Poe in put power 12V 1 A thanks..