TransferHandler problem

I've got Java 1.4 dragging between tables and lists in my application. Every drag and drop is a move, so when I drop an item onto one list, it is removed from the source.
Everything works great until I try to drag and drop on the same list. Seems like Swing first does the importData, then the exportDone, but because everything is serialized through the JVM, there doesn't seem to be a way to tell the transfer handler that the source and the target are the same object. How exactly do I teach my TransferHandler class to not importData if the source and target are the same.
Right now I'm cheating and saving the source of the drag as a static variable in the application class, but that doesn't seem like it should be the right way to do things. Is the new DnD code just poorly implemented, or am I missing something?
Oh, and I've tried saving the source component in the transfer data, but I get some weird null pointer exception somewhere in the UI classes when I do that.
Here's my TransferHandler class:
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.List;
import java.util.Vector;
import java.io.IOException;
* This handles the movement of CommentTextValues around the system.  Combined
* with properly build CommonTextModel and TermModel table and tree models,
* this method makes the dragging and dropping of common text and terms in an
* application completely generic.
public class TermSelection extends TransferHandler implements Transferable {
    // This looks a little weird, but it's because the TransferHandler is also the Transferable
    private static final DataFlavor[] flavors = {
            new DataFlavor(TermSelection.class, DataFlavor.javaJVMLocalObjectMimeType)
    // The data to be moved
    private List moving;
     * All this handler does is move operations; copy may be supported later if
     * the need arises.
    public int getSourceActions(JComponent c) {
        return MOVE;
     * Indicate what we can import (TermSelection objects).
    public boolean canImport(JComponent c, DataFlavor[] flavor) {
        if (c instanceof JTree || c instanceof JTable || c instanceof JList) {
            for (int idx = 0; idx < flavor.length; idx++) {
                if (flavor[idx].equals(flavors[0])) {
                    return true;
        return false;
     * Create the transferable object to pass to the drop listener.
     * @param component     the component that we're dragging from
     * @return  a loaded (set <b>moving</b>) Transferable object
    public Transferable createTransferable(JComponent component) {
        if (component instanceof JTable) {
            JTable table = (JTable) component;
            if (table.getModel() instanceof CommonTextModel) {
                CommonTextModel model = (CommonTextModel) table.getModel();
                // Get the selected items and save them for transfer
                int[] rows = table.getSelectedRows();
                List terms = model.getCommonText();
                moving = new Vector(rows.length);
                for (int idx = 0; idx < rows.length; idx++) {
                    moving.add(terms.get(rows[idx]));
                return this;
            } else if (table.getModel() instanceof TermModel) {
                TermModel model = (TermModel) table.getModel();
                // Get the selected items and save them for transfer
                int[] rows = table.getSelectedRows();
                List terms = model.getTerms();
                moving = new Vector(rows.length);
                for (int idx = 0; idx < rows.length; idx++) {
                    moving.add(terms.get(rows[idx]));
                return this;
        } else if (component instanceof JTree) {
            JTree tree = (JTree) component;
            if (tree.getModel() instanceof TermModel) {
//                TreePath path = tree.get
        } else if (component instanceof JList) {
            JList list = (JList) component;
            if (list.getModel() instanceof TermModel) {
                TermModel model = (TermModel) list.getModel();
                // Get the selected items and save them for transfer
                int[] rows = list.getSelectedIndices();
                List terms = model.getTerms();
                moving = new Vector(rows.length);
                for (int idx = 0; idx < rows.length; idx++) {
                    moving.add(terms.get(rows[idx]));
                return this;
        return null;
     * Import the data into components onto which they were dropped.  Supports
     * JTree and JTable components that have models implementing
     * CommonTextModel and TermModel.
     * @param c     the componet we're dropping on
     * @param t     the data object (with the moved values)
     * @return  true, if the drop was successful
    public boolean importData(JComponent c, Transferable t) {
        List moved = getWrapped(t);
        if (moved != null && t.isDataFlavorSupported(flavors[0])) {
            // Drop it on a tree?
            if (c instanceof JTree) {
                // Drop it on a terms tree?
                if (((JTree) c).getModel() instanceof TermModel) {
                    TermModel model = (TermModel) ((JTree) c).getModel();
                    model.addTerms(moved);
                    return true;
                // Drop it on a common text tree?
                // NOT YET IMPLEMENTED !!!
            // Drop it on the stop table or unreferenced terms table?
            } else if (c instanceof JTable) {
                JTable table = (JTable) c;
                if (table.getModel() instanceof CommonTextModel) {
                    CommonTextModel model = (CommonTextModel) table.getModel();
                    model.addCommonText(moved);
                    return true;
            } else if (c instanceof JList) {
                JList list = (JList) c;
                if (list.getModel() instanceof TermModel) {
                    TermModel model = (TermModel) list.getModel();
                    model.addTerms(moved);
                    return true;
        return false;
     * All drags in Rosetta are "moves" as opposed to "copies."  Remove the
     * objects from their source.
    protected void exportDone(JComponent source, Transferable data, int action) {
        List moved = getWrapped(data);
        if (moved != null) {
            if (source instanceof JTable) {
                JTable table = (JTable) source;
                if (table.getModel() instanceof CommonTextModel) {
                    CommonTextModel model = (CommonTextModel) table.getModel();
                    model.removeText(moved);
            } else if (source instanceof JList) {
                JList list = (JList) source;
                if (list.getModel() instanceof TermModel) {
                    TermModel model = (TermModel) list.getModel();
                    model.removeTerms(moved);
        super.exportDone(source, data, action);
     * Convert the transferable object to a wrapped object.
     * @param data
     * @return  returns null if the transferable object is not a Wrapped
     *          object, or an exception was thrown
    private static List getWrapped(Transferable data) {
        try {
            if (data.getTransferData(flavors[0]) instanceof List) {
                return (List) data.getTransferData(flavors[0]);
        } catch (UnsupportedFlavorException e) {
        } catch (IOException e) {
        return null;
    public DataFlavor[] getTransferDataFlavors() {
        return flavors;
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.equals(flavors[0]);
     * @param flavor    ignored; we always return the list
     * @return the list of CommonTextValue objects that we're dragging
     * @throws UnsupportedFlavorException   not thrown
     * @throws IOException  not thrown
    public Object getTransferData(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException {
        return moving;
}

You find an example here:
http://forum.java.sun.com/thread.jspa?threadID=646602

Similar Messages

  • JTree TransferHandler problems (SSCE inside)

    Hi JAvaers.
    Appreciate the help as always, hopefully one of you will pinpoint the demon. I'd have thought that I could build these gizmos eyes closed by now -- except for this one! I'm examining code against those that work, and I can't play the find-the-mistakes game successfully at all. Here's an SSCE that reproduces the problem:
    Expected Behavior:
    When I drag a node onto another node, it is simply deleted from its original parent.
    Actual Behavior:
    No deletion takes place.
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import java.io.*;
    * Dragging and dropping chocolate milk onto default category should remove
    * the node from its parent, but it doesn't. *puzzle*
    public class Test extends JFrame{
         private static final long serialVersionUID = 1L;
         private static Category root;
         static{
              root = new Category( "root category" );
              Category milk = new Category( "milk" );
              Category cmilk = new Category( "chocolate milk" );
              Category choco = new Category( "choco" );
              milk.add( cmilk );
              root.add( milk );
              root.add( choco );
         public static void main( String args[]) throws Exception {
              JFrame f = new JFrame();
              f.setSize( 400, 400 );
              f.getContentPane().add( new JScrollPane( new TestTree() ) );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setVisible( true );     
          * Our tree
         private static final class TestTree extends JTree {
              private static final long serialVersionUID = 1L;
              private DefaultTreeModel      model;
              private TreePath               selectedPath;
              private Category               originalTransferable;
              public TestTree(){
                   model = new DefaultTreeModel( root );
                   setModel( model );
                   setDragEnabled( true );
                   setTransferHandler( new TreeNodeTransferHandler() );
                   setDropMode( DropMode.ON_OR_INSERT );
                   addTreeSelectionListener( new TreeSelectionListener() {
                        public void valueChanged( TreeSelectionEvent e ){     
                             TreePath path = e.getNewLeadSelectionPath();
                             if( path != null ){
                                  selectedPath = path;
              private class TreeNodeTransferHandler extends TransferHandler {          
                   private static final long serialVersionUID = 1L;
                   public boolean importData( TransferSupport info ) {
                        if( !canImport(info) )
                           return false;     
                        try{
                            // fetch the drop location
                            JTree.DropLocation           dl                = (JTree.DropLocation)info.getDropLocation();
                            TreePath                     path           = dl.getPath();   
                            Category                    dragged          = (Category)info.getTransferable().getTransferData( Category.categoryFlavor );
                            Category                    target          = (Category)path.getLastPathComponent();
                            System.out.println(
                                      " --> Original transferable hashcode : " +
                                      originalTransferable.hashCode() +
                                      "\n --> Actual transferable hashcode : " +
                                      ((Category)info.getTransferable().getTransferData( Category.categoryFlavor )).hashCode()                       
                            System.out.println( "droppped " + dragged + " onto " + target );
                            // doesn't work
                            ((Category)dragged.getParent()).removeSubcategory( dragged, model );
                            // -- or --
                            // works
                            //((Category)originalTransferable.getParent()).removeSubcategory( originalTransferable, model );
                            return true;
                        catch( Exception x ){
                             x.printStackTrace();
                        return false;
                   public int getSourceActions( JComponent c ){
                        return TransferHandler.MOVE;
                   @Override
                   protected Transferable createTransferable( JComponent c ){
                        if( c.equals( TestTree.this ) ){          
                             if( selectedPath != null && !((Category)selectedPath.getLastPathComponent()).isRoot() ){
                                  originalTransferable = (Category)selectedPath.getLastPathComponent();
                                  return originalTransferable;
                        return null;
                   public boolean canImport( TransferSupport info ){
                        if( !info.isDrop() )
                             return false;
                        if( !info.isDataFlavorSupported( Category.categoryFlavor ) )
                           return false;
                        JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation();
                        if( dl == null || dl.getPath() == null )
                             return false;
                        Object transferdata   = null;
                        try{
                             transferdata = info.getTransferable().getTransferData( Category.categoryFlavor );
                        catch( Exception e ){
                             e.printStackTrace();
                        // can't drop a null node, nor can a node be dropped onto itself
                        return dl.getPath().getLastPathComponent() != null &&
                                  dl.getPath().getLastPathComponent() != transferdata;
          * Dummy node object
         private static final class Category extends DefaultMutableTreeNode implements Transferable{
              private static final long serialVersionUID = 1L;
              public static final DataFlavor categoryFlavor = new DataFlavor( Category.class, "Category" );
              public static final DataFlavor[] transferDataFlavors = new DataFlavor[]{ categoryFlavor };
              private String title;
              public Category( String t ){
                   title = t;
              @Override
              public String toString() {
                   return title;
              @Override
              public Object getTransferData(DataFlavor flavor)
                   throws UnsupportedFlavorException, IOException {
                   if( flavor.equals( categoryFlavor ) )
                        return this;
                   return null;
              @Override
              public DataFlavor[] getTransferDataFlavors() {
                   return transferDataFlavors;
              @Override
              public boolean isDataFlavorSupported(DataFlavor flavor) {
                   return flavor.equals( categoryFlavor );
               * Remove a child category from this category
               * @param n
              public void removeSubcategory( final Category n, final DefaultTreeModel model ){
                   int[]          childIndex   = new int[1];
                 Object[]    removedArray = new Object[1];                 
                 childIndex[0]                 = getIndex( n );
                 removedArray[0]            = n;       
                 remove( n );       
                 model.nodesWereRemoved( this, childIndex, removedArray );
    }Thanks again!
    Alex

    As other detail, if we resort to using the user objects inside of the Trasferables to transmit the categories themselves, it appears that the object integrity is maintained.
    so either:
    1 - Transferables are not guaranteed to be persistent in memory space
    2 - There's a bug here that is causing some kind of improper cloning of the transferables themselves, that is otherwise preserving their user objects.
    I'd call #2 a gotcha. I'll try bugging this at Sun to see if they'll fix it.

  • Problem with Drag and Drop (TransferHandler)

    I have a stern problem with the java.swing.TransferHandler. It shows a design weakness, and because of a tiny glitch I am currently not able to finish my task.
    The design weakness is that method importData(JComponent comp, Transferable t) does not pass the dropAction information in the parameter list. The application case in question is a transfer from a JTree to a JTree (might likewise be to/from a JList). The transfer semantics imply that partial success is possible (there are item identity and uniqueness considerations to handle). - I can deal with all detail demands except that I cannot discriminate between COPY and MOVE taking place in the transfer. Also I don't find any possibility to retrieve this information by subclassing TranferHandler or from any other element there.
    Is there any expert who knows a solution?

    I came up with two solutions. One is I modified my application requirements for the time being so the problem disappears. :)
    Second, I had the idea to create a subclass of javax.swing.TransferHandler and copy/override as many methods as necessary to allow for an extra method public boolean importData(JComponent comp, Transferable t, int action) and derive the extra value from a modified method DropHandler.drop(DropTargetDropEvent e) in a copy of the DropHandler.
    Whether this really works, I have not tested.
    As for your answer, Andre_Uhres, I don't find it elaborate enough that it leads to a solution, hence no stars rewarded. You leave it open how to get hold of the DropTarget events which are dealt with privately in javax.swing.TransferHandler.
    I consider the subject closed for my purposes. Thanks very much for your reply!

  • Problem- Set TransferHandler for JList

    Hi all,
    In the attached code, I set transfer handler to a Jlist. But when I click and drag it, the string given in println is not printed.
    This is the initial step which I did for set transfer handler to jlist and I believe it should get printed.
    Please point out if I have made any mistake in this.
         jlist.setTransferHandler(new TransferHandler()
                   List fileList;
                   boolean export = false;
                   List<File> newList = null;
                   protected Transferable createTransferable(JComponent c)
                        System.out.println("You entered create transferable");
                                    ........................................................Regards,
    Anees

    Hi,
    Did you tryjlist.setDragEnabled(true);
    Exactly that was the problem. Thanks mpmarrone .
    Also, camickr, after reading the tutorials only I posted this thread. Somehow, I missed this valuable point. Anyway thanks alot for your helping attitude.
    Anees

  • TransferHandler text "cut" action

    Hello,
    I've searched about these forums a bit, and haven't found any threads with answers; hopefully this one will be more successful!
    When installing a custom TransferHandler on a JTextComponent, the component's default behavior for Cut/Copy/Paste is overridden.
    I'm doing something special with Cut/Paste, so that's fine... But I would like to retain the standard "cut" action. In the TransferHandler, I find this method, which shows an action of MOVE on cut actions... Is this what I should capture?
    public void exportToClipboard(JComponent comp, Clipboard clip,
                       int action) throws IllegalStateException {
                  super.exportToClipboard(comp, clip, action);
                  if( action == MOVE ){
                       // cut the text here?
             }Is that where I should tap into the handler to remove the text? If so, what's the cleanest way to remove selected text from a JTextPane?
    Cheers.
    Alex

    -> When installing a custom TransferHandler on a JTextComponent, the component's default behavior for Cut/Copy/Paste is overridden.
    Do you write the TransferHandler from scratch or do you extend some other class. If so which class do you extend?
    -> I'm doing something special with Cut/Paste, so that's fine...
    ok
    -> But I would like to retain the standard "cut" action.
    but you just said you are doing something special with "cut"
    Maybe if you gave us your requirement we can suggest whether you are approaching the problem correctly. Is this strictly a "drag and drop" question. Or is this also a "cut" feature that is required when you use the Ctrl+X.

  • JTextPane and TransferHandler

    While trying to integrate another company's applet into our system, I realized I was going to have to write my own TransferHandler to handle pasting content from Microsoft Word. Soon after, I realized that you must also override other methods of TransferHandler so that copying, cutting and drag-and-drop all still work. I have been able to get most things working, but have had trouble with the createTransferable() method. The problem I am having is that the JComponent I am trying to allow copying from is a JTextPane with and underlying HTMLDocument. When I use the JTextPane.getSelectedText() method, I only get the bare text and not the underlying HTML code that I desire.
    I have searched high and low for a method to get the underlying HTML code which corresponds to the current selection in the JTextPane to no avail. Can anyone offer any insight into this conundrum?
    Thank you for your time and consideration.

    It's funny that no one has ever answered this question (or the many like it from before). I ended up finding the source for Java's default TransferHandler and seeing how it was grabbing the underlying HTML code. It all seems to make much more sense now, but it's not something I would have arrived at without the source to look at.
    You can find the source to the BasicTextUI.TextTransferHandler here -- http://www.javaresearch.org/source/jdk142/javax/swing/plaf/basic/BasicTextUI.java.html. Among other things, it shows how you go about "grabbing" the structure from the underlying document. Basically you use the EditorKit (or, in this case, the HTMLEditorKit) to read from the document and it take care of the "translation" for you. The important part goes something like this (minus try-catch blocks):
    Document doc = textPane.getDocument();
    EditorKit kit = textPane.getEditorKit();
    int beg = textPane.getSelectionStart();
    int end = textPane.getSelectionEnd();
    Position p0 = doc.createPosition(beg);
    Position p1 = doc.createPosition(end);
    StringWriter htmlOut = new StringWriter(p1.getOffset() - p0.getOffset());
    kit.write(htmlOut, doc, p0.getOffset(), p1.getOffset() - p0.getOffset());
    return htmlOut.toString();Now the only problem I need fixed is trying to get the EditorKit to stop from including all the structure from the entire ancestry of the current selection. For instance, if you select just one letter from a cell of a table that is nested in a div, inside another table, the resulting string from that single-character selection would be like this:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <table>
    <tr>
    <td>
    <div>
    <table><tr><td>X</td></tr></table>
    </div>
    </td>
    </tr>
    </table>
    </body>
    </html>Now if someone could just point out how to intelligently limit that return scope, I'd be one happy little coder! (I tried, unsuccessfully, to insert a marker like following, to no avail.)
    <!--Begin Marker-->
    the original selection goes here
    <!--End Marker-->

  • TransferHandler under the JDK 1.5

    There is a problem with TransferHandler in applet under the JDK 1.5.
    For example, try to execute an applet with the code from the classic sample of Tutorial http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html#cut. Any actions do not work through the menu items :-( Maybe are anyone who faced with this?

    These are obviously excellent reasons not to use stack smashing protection in the official Sun binaries.
    However, if one does not care for speed, there might be a small chance that it could be sane to compile the jvm on ones own with a stack smashing protection enabled compiler.
    concerning 4): The fact that Java prevents buffer overflows was one of the main reasons to use Java for this application. But I am also concerned about the very minuscule chance that the JVM itself might be attacked by a buffer overflow exploit. The Java application makes use of sockets to establish a data connection. Maybe there might be a bug in the jvm, which enables malicious TCP packets to crash the jvm and exploit a buffer overflow.
    Do I understand it correctly, that Sun does neither offers 1.5.0_00 -> 1.5.0_04 patches, nor the 1.5.0_04 source code, but only the 1.5.0_00 source code? Is this a concious decision (i.e. a Sun policy)?
    I could perfectly understand such a decision, because it could be a measure in order to force Java users to use the Java/Solaris/UltraSparc combination for cases where reliability/security really is mission critical, which would obviously be a sane business decision by Sun.
    But I only would like to make sure that I do understand the facts correctly: The source code is really only intended to be used for research purposes as it is not patched?

  • How to extend JTable's TransferHandler in 1.4.1?

    Has anyone successfully extended a JTable's TransferHandler in 1.4.0 or 1.4.1beta?
    Here is a simple working JTable DnD example but I need to be able to transfer data other than just strings (which is all that this example is designed to do) and the only way I can think of is to extend the TransferHandler (by default, in 1.4.1, JTable BasicTableUI has a TableTranserHandler class with a createTransferable method that is supposed to create a Transferable with various HTML tags but it doesn't seem to get called). I can't seem to do anything with the TransferHandler without clobbering the drag operation -- see bug report at the link shown below:
    http://developer.java.sun.com/developer/bugParade/bugs/4514071.html
    The bug shown above is supposedly fixed and closed but I think the problem still exists. I would appreciate anyone who can shed some light on this subject -- I've assign 5 dukes to this subject but if needed, I can assign more later.
    ;o)
    V.V.
    prog.java
    =========
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class AOKabc extends JApplet {
       static myMenu window;
       public void init() {
          initialize();
          window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
       public void stop() {
          window.dispose();
       public static void main(String[] args) {
          initialize();
          window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
       private static void initialize() {
          window = new myMenu("AOKabc");
          window.setVisible(true);
       static class myMenu extends JFrame {
          JScrollPane scrollPane;
          public myTable myTbl;
          JFrame frame=new JFrame();
          JPanel panel=new JPanel(new BorderLayout());
          public myMenu(String title) {
             super(title);
             setSize(800,600);
             Container contentPane = getContentPane();
             myTbl=new myTable(800,600);
             scrollPane=new JScrollPane(myTbl);
             panel.add("Center",scrollPane);
             contentPane.add(panel,BorderLayout.CENTER);
    }myTable.java
    ============
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    public class myTable extends JTable implements DropTargetListener {
       public static final int maxCol=26;
       public static final int maxRow=100;
       Object rowData[][]=new Object[maxRow][maxCol];
       Rectangle drawRect;
       private DropTarget dropTarget;
       myTable(int width, int height) {
          setPreferredScrollableViewportSize(new Dimension(width,height));
          TableModel TM=new AbstractTableModel() {
             public Object getValueAt(int row, int col) {
                if (rowData[row][col]==null) return "";
                return rowData[row][col];
             public int getColumnCount() {
                return maxCol;
             public int getRowCount() {
                return maxRow;
             public boolean isCellEditable(int row, int col) {
                return true;
             public void setValueAt(Object value, int row, int col) {
                rowData[row][col]=value;
                fireTableCellUpdated(row, col);
          setModel(TM);
          setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
          setCellSelectionEnabled(true);     // this basically turn off row selection highlighting
          getTableHeader().setReorderingAllowed(false);
          for (int i=0;i<maxCol;i++) getColumnModel().getColumn(i).setMinWidth(50);
          setDragEnabled(true);
    /*** uncomment the next lines and the drag stops working (it won't work even if it's followed by a call to updateUI() ***/
    //      setTransferHandler(new TransferHandler("Text"));
          dropTarget=new DropTarget(this,this);
       public void dropActionChanged(DropTargetDragEvent event) {}
       public void dragEnter(DropTargetDragEvent event) {}
       public void dragExit(DropTargetEvent event) {}
       public void dragOver(DropTargetDragEvent event) {}
       public void drop(DropTargetDropEvent event) {
          Transferable contents=event.getTransferable();
          if (contents!=null) {
             if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                   Point p=event.getLocation();
                   int row=rowAtPoint(p);
                   int col=columnAtPoint(p);
                   String line=(String)contents.getTransferData(DataFlavor.stringFlavor);
                   int start=0;
                   int end=line.indexOf("\n");
                   if (end<0) {
                      setValueAt(line,row,col);
                      return;
                   String[] tmp;
                   while (end<=line.length()) {
                      tmp=getStringArray(line.substring(start,end),'\t');
                      for (int j=0;j<tmp.length;j++) setValueAt(tmp[j],row,col+j);
                      row++;
                      start=end+1;
                      if (start>=line.length()) break;
                      end=line.substring(start).indexOf("\n");
                      if (end>=0) end+=start; else end=line.length();
                } catch (Throwable e) {
                   e.printStackTrace();
       private String[] getStringArray(String inStr, char ctkn) {
          String[] x;
          if (inStr.length()==0) {
             x=new String[1];
             x[0]="";
             return x;
          int i=0;
          String tmp="";
          ArrayList AL=new ArrayList(20);
          while (i<inStr.length()) {
             if (inStr.charAt(i)==ctkn) {
                AL.add(new String(tmp));
                tmp="";
             } else tmp+=inStr.charAt(i);
             i++;
          AL.add(new String(tmp));
          x=new String[AL.size()];
          for (i=0;i<AL.size();i++) x=(String)AL.get(i);
    return x;

    Finally revisited this problem and found that it's a matter of putting the horse before the cart....i.e., TransferHandler has to be set before drag is enabled.
    Consider ubject matter closed!
    ;o)
    V.V.

  • Drag and Drop issue in Jlist - Transferhandler not working

    Hi all,
    I have a problem associated with the drag and drop of components into a Jlist.
    When I drag component out of a Jlist, the control reaches inside transfer handler, but when I try to insert a component into the Jlist, the control does not reach inside Jlist transfer handler.
         jlist.setDropMode(DropMode.INSERT);
         jlist.setDragEnabled(true);
         jlist.setTransferHandler(new TransferHandler()
                   List fileList;
                   boolean export = false;
                   List<File> newList = null;
                   protected Transferable createTransferable(JComponent c)
                        System.out.println("inside handler");
                                    ..............................Please help me with this issue.
    Any help in this regard will be well appreciated with dukes.
    Regards,
    Anees

    AneesAhamed wrote:
    Hi all,
    I have a problem associated with the drag and drop of components into a Jlist.
    When I drag component out of a Jlist, the control reaches inside transfer handler, but when I try to insert a component into the Jlist, the control does not reach inside Jlist transfer handler.
    jlist.setDropMode(DropMode.INSERT);
    jlist.setDragEnabled(true);
    jlist.setTransferHandler(new TransferHandler()
                   List fileList;
                   boolean export = false;
                   List<File> newList = null;
                   protected Transferable createTransferable(JComponent c)
                        System.out.println("inside handler");
    ..............................Please help me with this issue.
    Any help in this regard will be well appreciated with dukes.If you're wondering why your createTransferable() method is not called when you drag from some other component and drop into the list it is because createTransferable() is called when you start dragging. So it would be the TransferHandler of the source component, not your target list, that has its createTransferable() called in that case.
    When the list is the target of a drag&drop you should see the canImport() method of your TransferHandler being called. Do a System.out(0 in that method as well and see if that is the case.

  • Swing Transferhandler prevents garbage collection of one Component

    While searching for memory leaks in my app I found out that an object wasn't garbage collected because of a static reference from javax.swing.TransferHandler.
    Once an app has called TransferHandler.exportAsDrag, TransferHandler keeps alive one static reference to a SwingDragGestureRecognizer.
        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
            int srcActions = getSourceActions(comp);
            // only mouse events supported for drag operations
         if (!(e instanceof MouseEvent)
                    // only support known actions
                    || !(action == COPY || action == MOVE || action == LINK)
                    // only support valid source actions
                    || (srcActions & action) == 0) {
                action = NONE;
            if (action != NONE && !GraphicsEnvironment.isHeadless()) {
             if (recognizer == null) {
              recognizer = new SwingDragGestureRecognizer(new DragHandler());
                recognizer.gestured(comp, (MouseEvent)e, srcActions, action);
         } else {
                exportDone(comp, null, NONE);
    ....As you can see there is a call to recognizer.gestured(comp, (MouseEvent)e, srcActions, action). This object saves a reference to the component comp.
    This means that the last Component for which the exportAsDrag method was called (and the gestured call was reached); and all objects refererred to by the Component can not be garbage collected.
    I think in a normal application this will be not much of a problem because it's only a reference to a single Component; but still I think this is not very nice.
    Should I report this as a bug somewhere?

    Something similar seems to happens to JInternalFrame.lastFocusOwner
    Oh well, I guess I shouldn't worry too much about single references; I don't think they immediately cause memory leaks..

  • Recording movement on screen as movie file, delay problem

    Hi i am working on a project which has a number of moving agents (just square squares moving around in an applet). Basically what i am trying to do is capture what is going on as a quicktime movie. I have it working to a certain extent. At the moment i have a streaming class which captures the screen using a recordFrame() method and saves the RGB values in an array which is buffered via the datasource and saved to disk using a data sink.
    The recordFrame() method is called every time i call the repaint method in my "moving agents" class (i.e the new positions of the agents in the applets). The problem is when the recordFrame() method is called it delays the update() method for the applet meaning it is not a true reflection of what would really happen if i had no data sink implemented.
    I am new to JMF and know this is probably not an ideal way to implement this so any ideas or pointers would be greatly appreciated!!
    Below is the snippets of my code:
    Class MovingObject
                   while(prey.getState() != deadState  && started)
                        //While agent has not reached the edge of the agentStage move 1 pixel to the right     
                        try
                        {     currentTime +=delay;
                             Thread.sleep(Math.max(0, currentTime -    System.currentTimeMillis()));
                        catch (InterruptedException e)
                             System.out.println(""+e);
                             break;
                        pred.update(stageMap);
                        sleep();
                        repaint();
                        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    public class RecordImageSequences implements Serializable
        Processor mediaProcessor;
        ScreenStream liveStream;
        DataSource dataSource;
        DataSink outputSink;
        BufferedImage image;
        Robot robot;
        public RecordImageSequences(String outputFilename,int x, int y, int width, int height) throws Exception
                  image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
            liveStream = new ScreenStream(x,y,width, height);
            dataSource = new DataSource(liveStream);
            VideoFormat formats[] = new VideoFormat[1];
            formats[0] = new VideoFormat(VideoFormat.RGB);
            mediaProcessor = Manager.createRealizedProcessor(
                new ProcessorModel(dataSource,
                    formats,
                    new FileTypeDescriptor(FileTypeDescriptor.QUICKTIME)));
            outputSink = Manager.createDataSink(
            mediaProcessor.getDataOutput(), new MediaLocator("file://movie.mov"));
            outputSink.open();
            mediaProcessor.start();
            outputSink.start();
        public void recordFrame()
                  liveStream.getFrame();
    import java.awt.Dimension;
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.Serializable;
    import javax.media.Buffer;
    import javax.media.Format;
    import javax.media.Time;
    import javax.media.format.RGBFormat;
    import javax.media.format.VideoFormat;
    import javax.media.protocol.BufferTransferHandler;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PushBufferDataSource;
    import javax.media.protocol.PushBufferStream;
    public class ScreenStream implements PushBufferStream, Serializable
        ContentDescriptor contentDesc = new ContentDescriptor(ContentDescriptor.RAW);
        int maxDataLength;
        Dimension size;
        RGBFormat rgbFormat;
        float frameRate = 2.5f;
        BufferTransferHandler transferHandler;
        int width, height, x, y;
        boolean streamEnded = false;
        boolean started = false;
        BufferedImage imageToBeRead = null;
        Robot robot;
        BufferedImage image = new BufferedImage(100,100, BufferedImage.TYPE_INT_RGB);
        public ScreenStream(int x, int y, int width, int height)
            this.width = width;
            this.height = height;
            this.x = x;
            this.y = y;
            size = new Dimension(width, height);
            maxDataLength = size.width * size.height * 3;
            rgbFormat = new RGBFormat(size, maxDataLength,
                                      Format.intArray,
                                      frameRate,
                                      32,
                                      0xFF0000, 0xFF00, 0xFF,
                                      1, size.width,
                                      VideoFormat.FALSE,
                                      RGBFormat.BIG_ENDIAN);
           try
                     robot = new Robot();
           catch(Exception e){}
           started = true;
        public ContentDescriptor getContentDescriptor()
            return contentDesc;
        public long getContentLength()
            return LENGTH_UNKNOWN;
        public boolean endOfStream()
            return streamEnded;
        int seqNo = 0;
        public Format getFormat()
            return rgbFormat;
        public void read(Buffer buffer) throws IOException
            if(streamEnded)
                buffer.setEOM(true);
                buffer.setOffset(0);
                buffer.setLength(0);
                return;
            Object outdata = buffer.getData();
            if (outdata == null || !(outdata.getClass() == Format.intArray) ||
                ((int[])outdata).length < maxDataLength)
                outdata = new int[maxDataLength];
                buffer.setData(outdata);
            buffer.setOffset(0);
            buffer.setFormat(rgbFormat );
            buffer.setTimeStamp( (long) (seqNo * (1000 / frameRate) * 1000000) );
            imageToBeRead = getImage();
            imageToBeRead.getRGB(0, 0, width, height,
                      (int[])outdata, 0, width);
            buffer.setSequenceNumber( seqNo );
            buffer.setLength(maxDataLength);
            buffer.setFlags(buffer.getFlags() | Buffer.FLAG_KEY_FRAME);
            buffer.setHeader( null );
            seqNo++;
            imageToBeRead = null;
            synchronized(this)
                notifyAll();
        public synchronized void setTransferHandler(BufferTransferHandler transferHandler)
            this.transferHandler = transferHandler;
            notifyAll();
        int i=0;
    public void getFrame()
        //while (started)
           //Wait till the previous image is read
         synchronized(this)
                while((imageToBeRead != null || transferHandler == null) && started)
                               try
                                   System.out.println("WAITING");
                                    wait();
                               catch(Exception exp){}
                 if (started && transferHandler != null)
                      imageToBeRead = getImage();
                System.out.println("CHEESE, Frame"+i+""+started);
                transferHandler.transferData(this);
                i++;
                       try
                            Thread.currentThread().sleep(10);
                            System.out.println("Wait");
                       catch (InterruptedException e) {}
         public BufferedImage getImage()
              return robot.createScreenCapture(new Rectangle(x, y, width, height));
        public void endStream()
            synchronized(this)
                while(imageToBeRead != null || transferHandler == null)
                    try
                              wait();
                catch(Exception exp){}
            streamEnded = true;
            started = false;
            transferHandler.transferData(this);
        public Object [] getControls()
            return new Object[0];
        public Object getControl(String controlType)
            return null;
    }  I would Appreciate any help with this, as i am completely new to JMF.

    After looking over it again the while loop in my MovingObject class should look like the following (the all important recordFrame() is missing).
    the recorder RecordImageSequences object would also be initialed in the MovingObject class, something like this:
    RecordImageSequences recorder = new RecordImageSequences(filename,appletTopLeftX,appletTopLeftY,appletWidth,appletHeight);
    //While the applet  is still running. i.e. the agent in the applet are  still                                                
    //moving around
    while(prey.getState() != deadState  && started)
    try
             //Simply delays the running thread, to allow a delay between update() calls
             currentTime +=delay;
         Thread.sleep(Math.max(0, currentTime -    System.currentTimeMillis()));
    catch (InterruptedException e)
           System.out.println(""+e);
         break;
    //This is using an external class to update the agents in the applet, in                                      //their new positions
    pred.update(s tageMap);
    //Reapints the applet, with the agents in the new positions
    repaint();
    /*********UPDATED******/
      //This method is called to record the newly updated applet
      recorder.recordFrame();
    /**********/UPDATED****/
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    }

  • TransferHandler, Drag and Drop

    Hi,
    I implemented DnD in our application using the TransferHandler. This works quite well. But now I have a problem...
    I have to change the action due to the target window. If I'm outside the source window I don't want the move, but I will show the copy cursor.
    Changing the getSourceAction doesn't help, as the name says its only called in the beginning.
    Does anyone have a solution for this?
    Thanks
    Mario

    Rolled my own, [can see it here|http://forums.crm.saeven.net/blog.php?b=2]
    Hope it helps.

  • DnD: custom TransferHandler and JTree

    Hi!
    I have seen a similar post like this one before, but there was no real answer.
    When I use the standard TransferHandler for DnD in a JTree, things work the way they should. However, when I use my own custom subclass of TransferHandler, no dragging behaviour is to be seen. Obviously, some crucial piece of code is missing from my class, but what is it?
    public class TopicTransferHandler extends TransferHandler {
        private TM4J_FSControllerFactory factory;
        private Object objectInTree = null;
        public TopicTransferHandler(TM4J_FSControllerFactory factory) {
         super();
         this.factory = factory;
        protected Transferable createTransferable(JComponent c) {
         Transferable trans = null;
         // if we are dragging from a tree (should always be the case)...
         if (c instanceof FSTree) {
             // then we let the HTMController construct a transferable from
             // the currently selected object in the tree
             FSTree tree = (FSTree) c;
             HandleTopicMirrorController mc =
              factory.createMirrorController(true);
             trans = mc.getTransferable(objectInTree);
             System.out.println("createTransferable(): " + trans);
         return trans;
        public int getSourceActions(JComponent c) {
         return COPY_OR_MOVE;
    }I appreciate any help!
    Dunk

    Hello!!
    I was having the same problem, but using the source code of TransferHandler and the tutorial I finally got it!! Eba!!
    /** Check http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html
    * @author Stenio L. Ferreira
    * Created on 20/08/2003
    * [email protected]
    import javax.swing.*;
    import java.awt.datatransfer.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.tree.*;
    import com.exactus.vbcomponentes.*;
    public class JTreeTransferHandler extends TransferHandler {
         protected Transferable createTransferable(JComponent c) {
              return new StringSelection(exportString(c));
         public int getSourceActions(JComponent c) {
              return COPY_OR_MOVE;
         protected String exportString(JComponent c) {
              DefaultMutableTreeNode treeNode =
                   (DefaultMutableTreeNode) ((JTree) c)
                        .getSelectionPath()
                        .getLastPathComponent();
              Node meuNode = (Node) treeNode.getUserObject();
              Integer result = new Integer(meuNode.getMeuId());
              return (result.toString());
         private static class DragHandler implements MouseMotionListener {
              MouseEvent firstMouseEvent;
              public void mousePressed(MouseEvent e) {
                   firstMouseEvent = e;
                   e.consume();
              public void mouseDragged(MouseEvent e) {
                   if (firstMouseEvent != null) {
                        e.consume();
                        int dx = Math.abs(e.getX() - firstMouseEvent.getX());
                        int dy = Math.abs(e.getY() - firstMouseEvent.getY());
                        //Arbitrarily define a 5-pixel shift as the
                        //official beginning of a drag.
                        if (dx > 5 || dy > 5) {
                             JComponent c = ((JTree) e.getSource());
                             JTreeTransferHandler th =
                                  (JTreeTransferHandler) c.getTransferHandler();
                             Transferable t = th.createTransferable(c);
                             th.exportDone(c, null, NONE);
                             firstMouseEvent = null;
              public void mouseReleased(MouseEvent e) {
                   firstMouseEvent = null;
              public void mouseMoved(MouseEvent e) {
    }Hope this helps!

  • Need help .. JTable problem!!!!!

    Is there any way to provide drag n drop feature within Jtable cells ....
    What I want to do is that ... I shud be able to drag a JTable cell to another JTable cell and the values of those two cell should interchange ....
    Is this even possible ??? Please help me as I m new to Java
    Thanx alot....

    Plus I have one more problem the column headers arnt appearing ..... So please help me ..... I need two things to be done ....
    1) Populate the tables using vectors, so that only that no of rows appear which are in table of my database ..
    2) Column headers shud show up...
    Here's my code ...
    * Drag.java
    package test;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    public class Drag extends javax.swing.JFrame {
         private String url = "jdbc:odbc:FAMS";
        private Connection con;
        private Statement stmt;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        public void populate()
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
               String query = "SELECT * FROM SubAllot";
            /* First clear the JTable */
            clearTable();
            /* get a handle for the JTable */
            javax.swing.table.TableModel model = table.getModel();
            int r = 0;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) ) {
                        /* for each row get the fields
                           note the use of Object - necessary
                           to put the values into the JTable */
                       Object nm = rs.getObject(1);
                       Object sup = rs.getObject(2);
                       Object pri = rs.getObject(3);
                       Object sal = rs.getObject(4);
                       Object tot = rs.getObject(5);
                       model.setValueAt(nm, r, 0);
                       model.setValueAt(sup, r, 1);
                       model.setValueAt(pri, r, 2);
                       model.setValueAt(sal, r, 3);
                       model.setValueAt(tot, r, 4);
                       r++;
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           private void clearTable(){
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            for (int i=0; i < numRows; i++) {
                for (int j=0; j < numCols; j++) {
                    model.setValueAt(null, i, j);
              private void writeTable(){
             /* First clear the table */
             emptyTable();
             Statement insertRow;// = con.prepareStatement(
             String baseString = "INSERT INTO SubAllot " +
                                        "VALUES ('";
             String insertString;
            int numRows = table.getRowCount();
            javax.swing.table.TableModel model = table.getModel();
           /* Integer sup, sal, tot;
            Double pri;
            Object o;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                 for (int r=0; r < numRows; r++) {
                      if (model.getValueAt(r, 0) != null){
                           insertString = baseString + model.getValueAt(r, 0)+"','";
                           insertString = insertString + model.getValueAt(r, 1)+"','";
                           insertString = insertString + model.getValueAt(r, 2)+"','";
                           insertString = insertString + model.getValueAt(r, 3)+"','";
                           insertString = insertString + model.getValueAt(r, 4)+"');";
                           System.out.println(insertString);
                          insertRow = con.createStatement();
                           insertRow.executeUpdate(insertString);
                           System.out.println("Writing Row " + r);
                insertRow.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           // clearTable();
           private void emptyTable(){
             /* Define the SQL Query to get all data from the database table */
            String query = "DELETE * FROM SubAllot";
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query */
                   stmt.executeUpdate(query);
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
               abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    String val = (String) model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.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);
    table.scrollRectToVisible(scrollRect);
    /** Creates new form Drag */
    public Drag() {
    initComponents();
    populate();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
    Class[] types = new Class [] {
    java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
    public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(table);
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setRowHeight(23);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    table.setTableHeader(null);
    jButton1.setText("UPDATE");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(18, 18, 18)
    .addComponent(jButton1)
    .addContainerGap(15, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(80, 80, 80)
    .addComponent(jButton1)))
    .addContainerGap(14, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    writeTable(); // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Drag().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

  • TransferHandler.importData()  lacks generality

    Hey there,
    I'm using a TransferHandler on a JTree. The problem is that the importData() method doesn't convey the semantics of the import. There is no way of finding out if the import occured due to a COPY or a MOVE, and the way that I need to handle the import is highly dependant on this.
    Seem like this is a fairly fundamental flaw, so hopefully It's an oversight on my behalf.
    Thanks for any help.

    I'm not sure I understand the problem. The component where the transfer is coming FROM can tell what type of transfer based on how it is started. If the transfer is a "move" it can remove data when the transfer is done.
    The component where the transfer is going TO shouldn't care.
    So you need to first ask yourself if the target really, really, really needs to know or whether there is a better design. If the target must know, I don't think you can use the transfer handler to find out.
    Kevin

Maybe you are looking for

  • Page fault error while calling reports from forms

    dear friends. when a report is called from forms, just before opening up of background engine the application gets hanged with page fault. One has to forcibly shut down the application before loggin again. The error mesage generated from log file is

  • Trimmed Video has sound but no picture

    I need to split a large video file in two. When I use the trim function and select the first half of the video, it works great. I get a file with just the first half of the video - great sound and picture. However, when I try and create a file contai

  • [HOWTO] Mplayer music daemon

    Hello fellow Archers, I recently noticed that XMMS2 was using 40% of my CPU (not sure how I missed it but it no doubt has something to do with my setup) and decided I needed to correct this. My plan was to initially write my own music server, but tha

  • It is possible to connect the magic mouse, magic trackpad and the apple wireless keyboard at once on the same Bluetooth network on the new iMac?

    I want to buy a new iMac but in my country the iMac just come with the magic mouse and I want the trackpad for the multitouch geastures. Can you help me with this question?

  • Problem in co01 workcenter upload

    Hi experts, I have a doubt in my bdc, in my bdc i am going to create production order in CO01. its working properly but after entered the date i want to click operation overview and change one particular routing workcenter. But all the workcenter hav