Drag and drop a jcomponent

I want to drag and drop a component like textbox in MS Word. I figured out that you can drag and drop image and text easily. However to drag and drop a component you may need JavaBeans Bridge for ActiveX.
I did a little bit of research for this. I came across a tutorial from a website:
http://www.javaworld.com/javaworld/jw-09-1998/jw-09-bridge.html
I am novice to JavaBeans Bridge for ActiveX and I have no idea how to incorporate this in my application.
Please help me.
Thanks,
Riddhi.

It's not advanced it's ESSENTIAL and is not possible to write by hand because the NetBeans regenerate the code.....
or "by hand" means to write
setBounds(217,131,24,37)??????????
I use this in DOS programms !!!!!! Pascal for DOS , FoxPro for DOS!!!!!

Similar Messages

  • Drag and Drop Image to native Application

    Hi there!
    I've spent quite a while now, searching for answers for my problem. I want to be able to drag and drop some JComponent - let's say a JPanel - to a native Windows application (like MS Office...). I know this is possible and I know that windows requires some special Image format (like DIB or Bitmap). Now comes the tricky part :-) I was not able till now, to get my custom Transferhandler to work to obtain this task. Does anyone have some code snippets which to something like this? Or does anyone have any good hints how to do this? I've really searched the whole net all over and didn't really find anything helpful ( not even here, or on the rockhoppertech site).
    I whould highly apprechiate some help!
    Thank you all in advance :-)
    Michael

    i have the same problem and Sun doesn't seem to have an answer to this question. The DnD works in Mac OS, but not on Window 2000/XP.

  • Drag and Drop of cell content between 2 tables

    Hi Guys,
    Iam into implementing drag and drop of cell contents between 2 different tables,say Table1 and Table2.(Iam not dragging and dropping rows or cells,Just copying the content of one cell to another).
    Have extended the java tutorial class "TableTransferHandler" and "StringTransferHandler" under http://java.sun.com/docs/books/tutorial/uiswing/examples/dnd/index.html#ExtendedDndDemo to satisfy my needs.
    The drag is enabled for Table1 and table2 as follows.
    jTable1.setDragEnabled(true);
    jTable1.setTransferHandler(new TableTransferHandler());
    jTable2.setDragEnabled(true);
    jTable2.setTransferHandler(new TableTransferHandler());
    Dont be taken aback with the code I have put.It just to show what I have done..
    My questions are put at the end of the post..
    //String Transfer Handler class.
    public abstract class StringTransferHandler extends TransferHandler {
        protected abstract String exportString(JComponent c);
        protected abstract void importString(JComponent c, String str);
        protected abstract void cleanup(JComponent c, boolean remove);
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection(exportString(c));
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        public boolean importData(JComponent c, 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;
        protected void exportDone(JComponent c, Transferable data, int action) {
            cleanup(c, action == MOVE);
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
              JTable table = (JTable)c;         
             int selColIndex = table.getSelectedColumn();
            for (int i = 0; i < flavors.length; i++) {
                if ((DataFlavor.stringFlavor.equals(flavors))&& (selColIndex !=0)) {
    return true;
    return false;
    }//TableTransferHandler classpublic class TableTransferHandler extends StringTransferHandler {
    private int[] rows = null;
    private int addIndex = -1; //Location where items were added
    private int addCount = 0; //Number of items added.
    protected String exportString(JComponent c) {
    JTable table = (JTable)c;
    rows = table.getSelectedRows();
    StringBuffer buff = new StringBuffer();
    int selRowIndex = table.getSelectedRow();
    int selColIndex = table.getSelectedColumn();
    String val = table.getValueAt(selRowIndex,selColIndex).toString();
    buff.append(val);
    return buff.toString();
    protected void importString(JComponent c, String str) {
    JTable target = (JTable)c;
    DefaultTableModel model = (DefaultTableModel)target.getModel();
    //int index = target.getSelectedRow();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    target.setValueAt(str, row, column);
    protected void cleanup(JComponent c, boolean remove) {
    }Now I want to put in the following functionality into my program...
    [1]prevent dragging and dropping text in to the same table.That means I dont want to drag a cell content from Table1  and drop to another cell in Table1. Want to drag and drop cell content only from Table1 to Table2.
    [2]Change cursor on a un-defined Target. That means how to prevent a drag from a particular column in Table1.Also how to prevent a drop to a particular column in Table2. How to change the cursor to a "NO-DRAG" cursoror "NO-DROP" cursor.
    Could it be done using Drag Source Listener and drop Target Listener?.
    If yes,How can these listeners attached to the table and how to do it?
    If No,How Could it be done?
    [3]Want to change the background colour of the cell being dragged and also the background colour of the target cell where the drop is made...
    [4]Is there any out of the box way to make an undo in the target cell(where drop was made) so that the old cell value is brought back.
    How can I extend my code to take care of the above said things.
    Any help or suggestions is greatly appreciated.....
    Edited by: Kohinoor on Jan 17, 2008 10:58 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi Guys,
    Iam into implementing drag and drop of cell contents between 2 different tables,say Table1 and Table2.(Iam not dragging and dropping rows or cells,Just copying the content of one cell to another).
    Have extended the java tutorial class "TableTransferHandler" and "StringTransferHandler" under http://java.sun.com/docs/books/tutorial/uiswing/examples/dnd/index.html#ExtendedDndDemo to satisfy my needs.
    The drag is enabled for Table1 and table2 as follows.
    jTable1.setDragEnabled(true);
    jTable1.setTransferHandler(new TableTransferHandler());
    jTable2.setDragEnabled(true);
    jTable2.setTransferHandler(new TableTransferHandler());
    Dont be taken aback with the code I have put.It just to show what I have done..
    My questions are put at the end of the post..
    //String Transfer Handler class.
    public abstract class StringTransferHandler extends TransferHandler {
        protected abstract String exportString(JComponent c);
        protected abstract void importString(JComponent c, String str);
        protected abstract void cleanup(JComponent c, boolean remove);
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection(exportString(c));
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        public boolean importData(JComponent c, 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;
        protected void exportDone(JComponent c, Transferable data, int action) {
            cleanup(c, action == MOVE);
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
              JTable table = (JTable)c;         
             int selColIndex = table.getSelectedColumn();
            for (int i = 0; i < flavors.length; i++) {
                if ((DataFlavor.stringFlavor.equals(flavors))&& (selColIndex !=0)) {
    return true;
    return false;
    }//TableTransferHandler classpublic class TableTransferHandler extends StringTransferHandler {
    private int[] rows = null;
    private int addIndex = -1; //Location where items were added
    private int addCount = 0; //Number of items added.
    protected String exportString(JComponent c) {
    JTable table = (JTable)c;
    rows = table.getSelectedRows();
    StringBuffer buff = new StringBuffer();
    int selRowIndex = table.getSelectedRow();
    int selColIndex = table.getSelectedColumn();
    String val = table.getValueAt(selRowIndex,selColIndex).toString();
    buff.append(val);
    return buff.toString();
    protected void importString(JComponent c, String str) {
    JTable target = (JTable)c;
    DefaultTableModel model = (DefaultTableModel)target.getModel();
    //int index = target.getSelectedRow();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    target.setValueAt(str, row, column);
    protected void cleanup(JComponent c, boolean remove) {
    }Now I want to put in the following functionality into my program...
    [1]prevent dragging and dropping text in to the same table.That means I dont want to drag a cell content from Table1  and drop to another cell in Table1. Want to drag and drop cell content only from Table1 to Table2.
    [2]Change cursor on a un-defined Target. That means how to prevent a drag from a particular column in Table1.Also how to prevent a drop to a particular column in Table2. How to change the cursor to a "NO-DRAG" cursoror "NO-DROP" cursor.
    Could it be done using Drag Source Listener and drop Target Listener?.
    If yes,How can these listeners attached to the table and how to do it?
    If No,How Could it be done?
    [3]Want to change the background colour of the cell being dragged and also the background colour of the target cell where the drop is made...
    [4]Is there any out of the box way to make an undo in the target cell(where drop was made) so that the old cell value is brought back.
    How can I extend my code to take care of the above said things.
    Any help or suggestions is greatly appreciated.....
    Edited by: Kohinoor on Jan 17, 2008 10:58 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to outline selected cells during drag and drop in the jtable

    Hi,
    I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
    Can anybody give me a tip, where to read more about this problem or even better, give an example...
    I have the following situation:
    1.Table has 10 rows and 10 columns
    2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
    3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
    4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
    5.rectangular disappears when dropped
    Regards,
    Primoz

    In "createTransferable" you can create a drag image
    which you can paint in "dragOver" and clear in "drop" method of DropTarget :
    package dnd;
    * DragDropJTableCellContents.java
    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.BufferedImage;
    import java.io.IOException;
    public class DragDropJTableCellContents extends JFrame {
        public DragDropJTableCellContents() {
            setTitle("Drag and Drop JTable");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
            setSize(400, 300);
            setLocationRelativeTo(null);
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            for (int i = 0; i < 10; i++) {
                model.addColumn("Column "+i);
            for (int i = 0; i < 10; i++) {
                String[] rowData = new String[10];
                for (int j = 0; j < 10; j++) {
                    rowData[j] = tableId + " " + i + j;
                model.addRow(rowData);
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setCellSelectionEnabled(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDragEnabled(true);
            TableTransferHandler th = new TableTransferHandler();
            table.setTransferHandler(th);
            table.setDropTarget(new TableDropTarget(th));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DragDropJTableCellContents().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            @Override
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            @Override
            public boolean importData(JComponent c, 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(JComponent c, 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;
            @Override
            protected Transferable createTransferable(JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                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(",");
                return buff.toString();
            protected void importString(JComponent c, 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){
    model.setValueAt(string, target.getSelectedRow(), colCount);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(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, 1f));
    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(TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(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(DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(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(JTable table, 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(JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTable table, 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);
    Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

  • Must click then click and drag for JTable Drag and Drop

    Hi All,
    I've been using Java 1.4 to drag and drop data between two tables in our application. Basically I need to drag the data from individual rows of the source table and insert it into one of the cells in the new table. This works absolutely fine and has made a huge improvement to this portion of our app. I've included example source code below that does a similar thing by transferring data from one table and inserting it into another (it's quite big and also not as well done as the example in our real app but unfortunately I can't send the source for that).
    The thing I've noticed though is that in order to start dragging data I need to click to select it and then press and hold the mouse button to start dragging, whereas under W**dows and just about every other OS you can just press and hold and start dragging straight away. If you try this with a JTable though it just changes the rows you have selected so the drag and drop works but feels a bit clunky and amateurish. I'd like to do something about this such that it works like Windows Explorer (or similar) where you can just press the mouse button and start dragging.
    Any help would be greatly appreciated - and if anybody finds the code useful you're more than welcome to it. Note that the business end of this is CustomTransferHandler.java - this will show you how to insert data at a specific position in a JTable, it's a bit of a faff but not too bad once you've got it sussed.
    Thanks,
    Bart Read
    ===============================================================
    TestFrame.java
    * TestFrame.java
    * Created on October 21, 2002, 4:59 PM
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.util.TooManyListenersException;
    import javax.swing.*;
    * @author  readb
    public class TestFrame extends javax.swing.JFrame
         private static final String [] NAMES     = {
              "John", "Geoff", "Madeleine", "Maria", "Flanders",
              "Homer", "Marge", "Bart", "Lisa", "Weird Baby" };
         private JTable source;
         private JTable dest;
         private MyTableModel     sourceModel;
         private MyTableModel     destModel;
         private Clipboard          clipboard;
         /** Creates a new instance of TestFrame */
         public TestFrame()
              clipboard = getToolkit().getSystemClipboard();
              Container c = getContentPane();
              c.setLayout( new BorderLayout( 40, 40 ) );
              source = new MyJTable();
              sourceModel = new MyTableModel();
              source.setModel( sourceModel );
              source.setDragEnabled( true );
              CustomTransferHandler handler = new CustomTransferHandler( "Source handler" );
              source.setTransferHandler( handler );
              try
                   source.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              dest = new MyJTable();
              destModel = new MyTableModel();
              dest.setModel( destModel );
              dest.setDragEnabled( true );
              handler = new CustomTransferHandler( "Dest handler" );
              dest.setTransferHandler( handler );
              try
                   dest.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              c.add( new JScrollPane( source ), BorderLayout.WEST );
              c.add( new JScrollPane( dest ), BorderLayout.EAST );
              populate();
         private void populate( MyTableModel model )
              for ( int index = 0; index < NAMES.length; ++index )
                   model.setRow( index, new DataRow( index + 1, NAMES[ index ] ) );
         private void populate()
              populate( sourceModel );
              populate( destModel );
         public static void main( String [] args )
              TestFrame app = new TestFrame();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing( WindowEvent we )
                             System.exit( 0 );
              app.pack();
              app.setSize( 1000, 600 );
              app.show();
         private class MyJTable extends JTable
              public boolean getScrollableTracksViewportHeight()
                   Component parent = getParent();
                   if (parent instanceof JViewport)
                        return parent.getHeight() > getPreferredSize().height;
                   return false;
    }=====================================================================
    MyTableModel.java
    * MyTableModel.java
    * Created on October 21, 2002, 4:43 PM
    import java.util.ArrayList;
    * @author  readb
    public class MyTableModel extends javax.swing.table.AbstractTableModel
         private static final int          NUMBER               = 0;
         private static final int          NAME               = 1;
         private static final String []     COLUMN_HEADINGS     = { "Number", "Name" };
         private ArrayList data;
         /** Creates a new instance of MyTableModel */
         public MyTableModel()
              super();
              data = new ArrayList();
         public int getColumnCount()
              return COLUMN_HEADINGS.length;
         public String getColumnName( int index )
              return COLUMN_HEADINGS[ index ];
         public Class getColumnClass( int index )
              switch ( index )
                   case NUMBER:
                        return Integer.class;
                   case NAME:
                        return String.class;
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + index );
         public int getRowCount()
              return ( null == data ? 0 : data.size() );
         public Object getValueAt( int row, int column )
              DataRow dataRow = ( DataRow ) data.get( row );
              switch ( column )
                   case NUMBER:
                        return new Integer( dataRow.getNumber() );
                   case NAME:
                        return dataRow.getName();
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + column );
         public void addRow( DataRow row )
              int rowIndex = data.size();
              data.add( row );
              fireTableRowsInserted( rowIndex, rowIndex );
         public void addRows( DataRow [] rows )
              int firstRow = data.size();
              for ( int index = 0; index < rows.length; ++index )
                   data.add( rows[ index ] );
              fireTableRowsInserted( firstRow, data.size() - 1 );
         public void setRow( int index, DataRow row )
              if ( index == data.size() )
                   data.add( row );
              else
                   data.set( index, row );
              fireTableRowsUpdated( index, index );
         public void insertRows( int index, DataRow [] rows )
              for ( int rowIndex = rows.length - 1; rowIndex >= 0; --rowIndex )
                   data.add( index, rows[ rowIndex ] );
              fireTableRowsInserted( index, index + rows.length - 1 );
         public DataRow getRow( int index )
              return ( DataRow ) data.get( index );
         public DataRow removeRow( int index )
              DataRow retVal = ( DataRow ) data.remove( index );
              fireTableRowsDeleted( index, index );
              return retVal;
         public boolean removeRow( DataRow row )
              int index = data.indexOf( row );
              boolean retVal = data.remove( row );
              fireTableRowsDeleted( index, index );
              return retVal;
         public void removeRows( DataRow [] rows )
              for ( int index = 0; index < rows.length; ++index )
                   data.remove( rows[ index ] );
              fireTableDataChanged();
    }=====================================================================
    DataRow.java
    * DataRow.java
    * Created on October 21, 2002, 4:41 PM
    import java.io.Serializable;
    * @author  readb
    public class DataRow implements Serializable
         private int          number;
         private String     name;
         /** Creates a new instance of DataRow */
         public DataRow( int number, String name )
              this.number = number;
              this.name = name;
         public int getNumber()
              return number;
         public String getName()
              return name;
         public String toString()
              return String.valueOf( number ) + ": " + name;
    }======================================================================
    CustomTransferHandler.java
    * CustomTransferHandler.java
    * Created on October 22, 2002, 8:36 AM
    import java.awt.*;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.ClipboardOwner;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.*;
    import java.awt.event.InputEvent;
    import java.io.IOException;
    import java.util.Arrays;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JTable;
    import javax.swing.TransferHandler;
    * @author  readb
    public class CustomTransferHandler
                   extends TransferHandler
                   implements Transferable, ClipboardOwner, DropTargetListener
         public static final DataFlavor     ROW_ARRAY_FLAVOR     = new DataFlavor( DataRow[].class, "Multiple rows of data" );
         private String               name;
         private ImageIcon          myIcon;
         private     DataRow []          data;
         private boolean               clipboardOwner                    = false;
         private int                    rowIndex                         = -1;
         /** Creates a new instance of CustomTransferHandler */
         public CustomTransferHandler( String name )
              this.name = name;
         public boolean canImport( JComponent comp, DataFlavor [] transferFlavors )
              System.err.println( "CustomTransferHandler::canImport" );
              if ( comp instanceof JTable && ( ( JTable ) comp ).getModel() instanceof MyTableModel )
                   for ( int index = 0; index < transferFlavors.length; ++index )
                        if ( ! transferFlavors[ index ].equals( ROW_ARRAY_FLAVOR ) )
                             return false;
                   return true;
              else
                   return false;
         protected Transferable createTransferable( JComponent c )
              System.err.println( "CustomTransferHandler::createTransferable" );
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   return null;
              this.data = null;
              JTable               table     = ( JTable ) c;
              MyTableModel     model     = ( MyTableModel ) table.getModel();
              Clipboard          cb          = table.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
              clipboardOwner = true;
              int [] selectedRows = table.getSelectedRows();
              Arrays.sort( selectedRows );
              data = new DataRow[ selectedRows.length ];
              for ( int index = 0; index < data.length; ++index )
                   data[ index ] = model.getRow( selectedRows[ index ] );
              return this;
         public void exportAsDrag( JComponent comp, InputEvent e, int action )
              super.exportAsDrag( comp, e, action );
              Clipboard          cb          = comp.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
         protected void exportDone( JComponent source, Transferable data, int action )
              System.err.println( "CustomTransferHandler::exportDone" );
              if ( TransferHandler.MOVE == action && source instanceof JTable && ( ( JTable ) source ).getModel() instanceof MyTableModel )
                   JTable table = ( JTable ) source;
                   MyTableModel model = ( MyTableModel ) table.getModel();
                   int [] selected = table.getSelectedRows();
                   for ( int index = selected.length - 1; index >= 0; --index )
                        model.removeRow( selected[ index ] );
         public void exportToClipboard( JComponent comp, Clipboard clip, int action )
              System.err.println( "CustomTransferHandler::exportToClipboard" );
         public int getSourceActions( JComponent c )
              System.err.println( "CustomTransferHandler::getSourceActions" );
              if ( ( c instanceof JTable ) && ( ( JTable ) c ).getModel() instanceof MyTableModel )
                   return MOVE;
              else
                   return NONE;
          *     I've commented this out because it doesn't appear to work in any case.
          *     The image isn't null but as far as I can tell this method is never
          *     invoked.
    //     public Icon getVisualRepresentation( Transferable t )
    //          System.err.println( "CustomTransferHandler::getVisualRepresentation" );
    //          if ( t instanceof CustomTransferHandler )
    //               if ( null == myIcon )
    //                    try
    //                         myIcon = new ImageIcon( getClass().getClassLoader().getResource( "dragimage.gif" ) );
    //                    catch ( Exception e )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: exception loading image" );
    //                         e.printStackTrace();
    //                    if ( null == myIcon )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: myIcon is still NULL" );
    //               return myIcon;
    //          else
    //               return null;
         public boolean importData( JComponent comp, Transferable t )
              System.err.println( "CustomTransferHandler::importData" );
              super.importData( comp, t );
              if ( ! ( comp instanceof JTable ) )
                   return false;
              if ( ! ( ( ( JTable ) comp ).getModel() instanceof MyTableModel ) )
                   return false;
              if ( clipboardOwner )
                   return false;
              if ( !t.isDataFlavorSupported( ROW_ARRAY_FLAVOR ) )
                   return false;
              try
                   data = ( DataRow [] ) t.getTransferData( ROW_ARRAY_FLAVOR );
                   return true;
              catch ( IOException ioe )
                   data = null;
                   return false;
              catch ( UnsupportedFlavorException ufe )
                   data = null;
                   return false;
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
              System.err.println( "MyTransferable::getTransferData" );
              if ( flavor.equals( ROW_ARRAY_FLAVOR ) )
                   return data;
              else
                   throw new UnsupportedFlavorException( flavor );
         public DataFlavor[] getTransferDataFlavors()
              System.err.println( "MyTransferable::getTransferDataFlavors" );
              DataFlavor [] flavors = new DataFlavor[ 1 ];
              flavors[ 0 ] = ROW_ARRAY_FLAVOR;
              return flavors;
         public boolean isDataFlavorSupported( DataFlavor flavor )
              System.err.println( "MyTransferable::isDataFlavorSupported" );
              return flavor.equals( ROW_ARRAY_FLAVOR );
         public void lostOwnership( Clipboard clipboard, Transferable transferable )
              clipboardOwner = false;
         /** Called while a drag operation is ongoing, when the mouse pointer enters
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragEnter(DropTargetDragEvent dtde)
         /** Called while a drag operation is ongoing, when the mouse pointer has
          * exited the operable part of the drop site for the
          * <code>DropTarget</code> registered with this listener.
          * @param dte the <code>DropTargetEvent</code>
         public void dragExit(DropTargetEvent dte)
         /** Called when a drag operation is ongoing, while the mouse pointer is still
          * over the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragOver(DropTargetDragEvent dtde)
         /** Called when the drag operation has terminated with a drop on
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * <p>
          * This method is responsible for undertaking
          * the transfer of the data associated with the
          * gesture. The <code>DropTargetDropEvent</code>
          * provides a means to obtain a <code>Transferable</code>
          * object that represents the data object(s) to
          * be transfered.<P>
          * From this method, the <code>DropTargetListener</code>
          * shall accept or reject the drop via the
          * acceptDrop(int dropAction) or rejectDrop() methods of the
          * <code>DropTargetDropEvent</code> parameter.
          * <P>
          * Subsequent to acceptDrop(), but not before,
          * <code>DropTargetDropEvent</code>'s getTransferable()
          * method may be invoked, and data transfer may be
          * performed via the returned <code>Transferable</code>'s
          * getTransferData() method.
          * <P>
          * At the completion of a drop, an implementation
          * of this method is required to signal the success/failure
          * of the drop by passing an appropriate
          * <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
          * dropComplete(boolean success) method.
          * <P>
          * Note: The data transfer should be completed before the call  to the
          * <code>DropTargetDropEvent</code>'s dropComplete(boolean success) method.
          * After that, a call to the getTransferData() method of the
          * <code>Transferable</code> returned by
          * <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to
          * succeed only if the data transfer is local; that is, only if
          * <code>DropTargetDropEvent.isLocalTransfer()</code> returns
          * <code>true</code>. Otherwise, the behavior of the call is
          * implementation-dependent.
          * <P>
          * @param dtde the <code>DropTargetDropEvent</code>
         public void drop(DropTargetDropEvent dtde)
              System.err.println( "CustomTransferHandler::drop" );
              Component c = dtde.getDropTargetContext().getDropTarget().getComponent();
              if ( ! ( c instanceof JComponent ) )
                   dtde.rejectDrop();
                   return;
              JComponent comp = ( JComponent ) c;
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   dtde.rejectDrop();
                   return;
              dtde.acceptDrop( TransferHandler.MOVE );
              //     THIS is such a mess -- you can't do the following because
              //     getTransferable() throws an (undocumented) exception - what's that
              //     all about.
    //          Transferable t = dtde.getTransferable();
    //               if ( !t.isDataFlavourSupported( ROW_ARRAY_FLAVOR ) )
    //                    dtde.rejectDrop();
    //                    return false;
    //          TransferHandler handler = comp.getTransferHandler();
    //          if ( null == handler || ! handler.importData( comp, t ) )
    //               dtde.rejectDrop();
    //               return;
              Point p = dtde.getLocation();
              JTable table = ( JTable ) comp;
              rowIndex = table.rowAtPoint( p );
              //     So you have to do this instead and use the data that's been
              //     stored in the data member via import data.  Total mess.
              if ( null == data )
                   dtde.rejectDrop();
                   return;
              MyTableModel model = ( MyTableModel ) table.getModel();
              if ( rowIndex == -1 )
                   model.addRows( data );
              else
                   model.insertRows( rowIndex, data );
              dtde.acceptDrop( TransferHandler.MOVE );
         /** Called if the user has modified
          * the current drop gesture.
          * <P>
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dropActionChanged(DropTargetDragEvent dtde)
    }

    Hi again,
    Well I've tried using the MouseListener / MouseMotionListener approach but it doesn't quite seem to work, although it does get the events correctly. I think the reason is that it doesn't interact correctly with the Java DnD machinery which is something that V.V hinted at. It's something that I may need to look into if / when I have more time available.
    I have to say though that I haven't had any problems with scrollbars - we're making fairly heavy use of large tables and if you drag over a table with a scroll bar and move to the top or bottom then it scrolls as you would expect and allows you to drop the data where you like. For this situation I've used pretty much the same approach as for the toy example above except that I've implemented separate source and destination TransferHandlers (the source table is read-only, and it really doesn't make sense to allow people to drag from the destination table so I've essentially split the functionality of the example handler down the middle).
    I'm not actually particularly in favour of messing too much with the mechanics of DnD, more because of lack of time than anything else. Guess I'll just have to put up with this for the moment. Doesn't help that DnD is so poorly documented by Sun.
    Thanks for all your help.
    Bart

  • Drag and Drop Export Done is called too soon...

    Hi,
    I am trying to drag and drop a JLabel from a JPanel into another JPanel. I am no where near to figuring it out, but just for starters I notice that the exportDone() method is called in my custom TransferHandler immediately when the drag begins. Even stranger, createTransferable() is never called. (I am comparing my code to the DragPictureDemo that I found online). The question is, why is exportDone called immediately? Code below. Thanks. (BTW, any other suggestions about what I'm trying to do would be appreciated. I'm not confident in the direction I'm taking here... have yet to understand the Swing DnD mechanism...)
    From DragPictureDemo, I notice that createTransferable and exportAsDrag are called immediately upon drag, and exportDone is called at the drop.
    Here is my code: First, the main class Testola.java:
    * Created on Oct 31, 2007
    * Copyright 2006 Michael Anthony Schwager.
    * This software comes without warranty or applicability for any purpose.
    * Rights granted for any use.
    package testola;
    import javax.swing.*;
    import java.awt.*;
    public class Testola implements Runnable {
          * @param args
         public void run() {
              /*char[] stdout_arr={};
              String blah;
              blah=new String(stdout_arr, 0, 0);
              StringBuffer buf=null;
              System.out.println("Hello world." + " wow" + null + "<-null");*/
              // --------- FRAME ---------
              JFrame frame=new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(30,30,500,400);
            JDesktopPane dtp=new JDesktopPane();
            frame.getContentPane().add(dtp);
            // First Internal Frame; false means no close box.
            JInternalFrame jif=new JInternalFrame("One", true, false, true, true     ); //jif.setBounds(0,0,100,50);
            DnDJPanel contentPanel=new DnDJPanel(); contentPanel.setBackground(new Color(255,255,180));
            contentPanel.setLayout(null);
            // Then JLabels, first 1
            JLabel test1=new JLabel("test1!"); test1.setBounds(0, 0, 50, 20);
            test1.setBorder(BorderFactory.createLineBorder(Color.RED));
            //test1.setTransferHandler(new JComponentTransferHandler());
            contentPanel.add(test1);
            // 2
            JLabel test2=new JLabel("test2!"); test2.setBounds(10, 30, 50, 20);
            test2.setBorder(BorderFactory.createLineBorder(Color.GREEN));
            //test1.setTransferHandler(new JComponentTransferHandler());
            contentPanel.add(test2);
            // Finalize Frame
            contentPanel.setBounds(0,0,250,140);
            contentPanel.setTransferHandler(new JComponentTransferHandler());
            contentPanel.setVisible(true);
            jif.setBounds(10,10,250,140);
            jif.setContentPane(contentPanel);
            jif.setVisible(true);
            // Second Internal Frame
            DnDJInternalFrame jif2=new DnDJInternalFrame("Two", true, false, true, true     );
            // JPanel and jtextfield to add to Frame2
            // Finalize Frame2
            jif2.getContentPane().setLayout(null);
            jif2.setBounds(120,150,200,155);
            jif2.setVisible(true);
            dtp.add(jif);
            dtp.add(jif2);
            try {jif.setIcon(false);} catch (Exception e) {System.err.println("setIcon exception");}
              frame.setVisible(true);
         public static void main(String[] args) {
              Testola testola=new Testola();
              try {EventQueue.invokeAndWait(testola);} catch (Exception e) { System.out.println(e);};
              //testola.run();
              System.out.println("Exit");
    }Now, my JComponentTransferHandler.java:
    * Created on Apr 12, 2008
    * Copyright 2006 Michael Anthony Schwager.
    * This file is part of testola.
    * testola is free software; you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation; either version 2 of the License, or
    * (at your option) any later version.
    * testola is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    *  (You should have received a copy of the GNU General Public License
    *  along with testola; if not, write to the Free Software
    *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    package testola;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.event.InputEvent;
    import javax.swing.JComponent;
    import javax.swing.TransferHandler;
    public class JComponentTransferHandler extends TransferHandler {
         public JComponentTransferHandler() {
              super();
         public JComponentTransferHandler(String property) {
              super(property);
         public void exportDone(JComponent source, Transferable data, int action) {
              super.exportDone(source, data, action);
              System.out.println("Export is done!");
         public boolean importData(JComponent comp, Transferable t) {
              boolean res;
              res=super.importData(comp, t);
              System.out.println("Import is done! " + res);
              return res;
         public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
              boolean res;
              res=super.canImport(comp, transferFlavors);
              System.out.println("Can import: " + res);
              return res;
        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
             super.exportAsDrag(comp, e, action);
             System.out.println("Export as drag: " + comp.getClass().getName());
        protected Transferable createTransferable(JComponent c) {
            System.out.println("createTransferable, arg: " + c.getClass().getName());
             Transferable t=super.createTransferable(c);
            return t;
    }Edited by: Hushpuppy on Apr 13, 2008 7:59 PM
    Edited by: Hushpuppy on Apr 13, 2008 8:02 PM
    Edited by: Hushpuppy on Apr 13, 2008 8:13 PM

    No idea whether this will be helpful, but exportDone() is not called immediately if you remove the call to super.exportAsDrag.
    db
    edit Since your earlier post, I've been trying to teach myself Swing DnD, but am finding the documentation confusing and the tutorials primitive... I'd reached a conclusion, which has every chance of being wrong, that I should call createTransferable from exportAsDrag. FWIW these are the methods as of now -- nothing works :-(   @Override
       public void exportAsDrag(JComponent comp, InputEvent e, int action) {
          // count is a instance field to monitor repeated calls
          System.out.println(count + ". " + "exportAsDrag"); count++;
          //super.exportAsDrag(comp, e, action);
          // dragSource is a instance field of type Container
          dragSource = comp.getParent();
          createTransferable(comp);
       @Override
       protected Transferable createTransferable(JComponent child) {
          System.out.println(count + ". " + "createTransferable"); count++;
          // ComponentHandler implements Transferable
          Transferable t = new ComponentHandler(child);
          return t;
       }The commented line is from testing a possible cause of your problem, since my code never gets as far as exportDone() :-(
    Edited by: Darryl.Burke

  • Drag and drop images from document in pages 5.5

    Hey guys,
    So prior to updating my OS to Yosemite and my pages application to 5.5, i used to be able to select an image, hit the format button to the top right -> image tab and see the image file, then i could just drag and drop that file to my desktop (or wherever). Now i don't have that option? To get around this i've been renaming my file to a .zip and extracting it, but this is just a pain in the butt! Am i missing something, can i still do this and i just can't find it?
    Thanks!

    To be more precise, you can setup a JComponent or JPanel on top of your JavaFX nodes that has a TransferHandler that can convert the (AWT/Swing) images dragged to the app to JavaFX image and then insert it into the underlying node.
    As for the file chooser itselft: ListView and the JavaFX composer can allow you to create one quite easily. TreeView can aslso be used to a lesser extend (still a big buggy). For both of these, there are small bugs in the Cell API that may (or may not) prevent from displaying a proper thumbnail in the cells.
    You can also use a regular JFileChooser if you do not mind the dialog box having a different LnF from the rest of your application.

  • Drag and Drop (Trying to do a copy but it does a Move instead)?

    I have implemented drag and drop throughout my application and it works fine as long as I drag from a non-editable component (Table, TextArea, etc.) to an editable component (TextArea or TextField). However, When I drag and drop from an editable component to another editable component it does a move instead. How do I force it to do a copy? I looked at the description of exportAsDrag(JComponent comp, InputEvent e, int action) method and it even says for the action that no matter what you put in there "...the value may be changed during the course of the drag operation". What exactly causes this possible change and how do I prevent it from happening?
    This is the constructor I currently have:
    public TextAreaPanel(Document doc)
      super(doc);
      setMargin(new Insets(12,12,12,12));
      setDragEnabled(true);
      addMouseListener(new MouseAdapter()
        @Override public void mousePressed(MouseEvent e)
          if(e.getButton() != MouseEvent.BUTTON1)
            TextAreaPanel area = (TextAreaPanel)e.getSource();
            area.getTransferHandler().exportAsDrag(area, e, TransferHandler.COPY);
    }I forgot to mention before. The location of the component having the text copied into it is in a different JInternalFrame than the one where the text is being copied from (not sure if that matters or not).
    Edited by: Dont_Know on Jan 18, 2008 6:25 AM
    Edited by: Dont_Know on Jan 18, 2008 6:28 AM

    If your problem persists get yourself a micro USB cable (sold separately), you can restore your Apple TV from iTunes:
    Remove ALL cables from Apple TV. (if you don't you will not see Apple TV in the iTunes Source list)
    Connect the micro USB cable to the Apple TV and to your computer.
    Open iTunes.
    Select your Apple TV in the Source list, and then click Restore.

  • Drag and Drop in a JTable (ContentTable)

    Hello Friends,
    I am designing a tool which can be used for daily task distribution, according to time (as we setup in a outlook calendar) using JTable.
    Now I am planning to use a Drag and Drop option where in the task from "one date and time" can be moved to "another date and time" i.e row/column.
    E.g : Suppose the new task which is scheduled at 12:30pm on 22/03/07 has to be rescheduled at 3:00pm 26/03/07. The drag and drop should automatically recognise.
    It would be greate if anyone can throw in thier ideas.. 10 DUKE points..
    Thanks and Rgds,
    Pradeep

    Here's an example of drag and drop of a cell in JTable.
    You can move or copy (using Ctrl) a cell to another location:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.StringSelection;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.TransferHandler;
    import javax.swing.table.DefaultTableModel;
    public class DnD_Demo extends JFrame {
        public DnD_Demo() {
            setTitle("DnD Demo (Version 3)");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(1,1));
            panel.add(createTable("Table A"));
            getContentPane().add(panel,BorderLayout.CENTER);
            pack();
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            model.addColumn("Column 0");
            model.addColumn("Column 1");
            model.addColumn("Column 2");
            model.addColumn("Column 3");
            model.addRow(new String[]{tableId+" 00", tableId+" 01", tableId+" 02", tableId+" 03"});
            model.addRow(new String[]{tableId+" 10", tableId+" 11", tableId+" 12", tableId+" 13"});
            model.addRow(new String[]{tableId+" 20", tableId+" 21", tableId+" 22", tableId+" 23"});
            model.addRow(new String[]{tableId+" 30", tableId+" 31", tableId+" 32", tableId+" 33"});
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(400,100));
            table.setDragEnabled(true);
            table.setTransferHandler(new TableTransferHandler());
            JPanel panel = new JPanel();
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DnD_Demo().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            protected abstract void cleanup(JComponent c, boolean remove);
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            public int getSourceActions(JComponent c) {
                return COPY_OR_MOVE;
            public boolean importData(JComponent c, 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;
            protected void exportDone(JComponent c, Transferable data, int action) {
                cleanup(c, action == MOVE);
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.stringFlavor.equals(flavors)) {
    return true;
    return false;
    class TableTransferHandler extends StringTransferHandler {
    public JTable target;
    public int row = -1;
    public int col = -1;
    protected String exportString(JComponent c) {
    JTable table = (JTable)c;
    row = table.getSelectedRow();
    col = table.getSelectedColumn();
    return table.getValueAt(row, col).toString();
    protected void importString(JComponent c, String str) {
    target = (JTable)c;
    int row = target.getSelectedRow();
    int col = target.getSelectedColumn();
    target.getModel().setValueAt(str, row, col);
    protected void cleanup(JComponent c, boolean remove) {
    JTable table = (JTable)c;
    if (remove)
    table.getModel().setValueAt("", row, col);
    Message was edited by:
    Rodney_McKay

  • Autoscrolling in a DropTarget (Drag and Drop)

    I have implemented Drag and Drop using DropTargets and a DragSource And DragGestureListener.
    The DropTarget I have is a customized JComponent. How can I make the DropTarget autoscroll for Drag and Drop events??

    Have you tried adding a MouseMotionListener to the target component and checking to see if the mouse coordinates are near the edge of the viewable area?

  • Autoscrolling in the DropTarget (Drag and Drop)

    I have implemented Drag and Drop using DropTargets and a DragSource And DragGestureListener.
    The DropTarget I have is a customized JComponent. How can I make the DropTarget autoscroll for Drag and Drop events??

    Have you tried adding a MouseMotionListener to the target component and checking to see if the mouse coordinates are near the edge of the viewable area?

  • Drag and drop to Windows desktop

    Hi
    I've been struggling with this for a while, I've got a TransferHandler class that allows drag and drop from Windows desktop to application, now I'd like to do the reverse, but can't seem to provide the suitable DataFlavor to the OS, I'm using javaFileListFlavor obviously. I am currently creating a Transferable with createTransferable, but this is a StringSelection, and I can't remove this because I need it for internal drag and drop in the application. Please advise.
    public class CDrag extends TransferHandler {
        public CDrag(TreeTableView ttv) {
            this.ttv = ttv;
            dndData = new ArrayList();
            relPath = "/";
            try {
                uriFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
            } catch (ClassNotFoundException e) {
        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        @Override
        protected Transferable createTransferable(JComponent c) {
            String nodes = "";
            int j = 0;
            TreePath[] sel = ttv.treeTable.getTreeSelectionModel().getSelectionPaths();
            for (TreePath i : sel) {
                FileNode fNode = (FileNode) i.getLastPathComponent();
                if (j > 0) {
                    nodes = nodes + "\n";
                nodes = nodes + fNode.toString();
                j++;
            return new StringSelection(nodes);
        @Override
        protected void exportDone(JComponent c, Transferable t, int action) {
            if (!dndData.isEmpty()) {
                File[] sg = (File[]) dndData.toArray();
             // delete files that are dropped
                dndData.clear();
        @Override
        public boolean canImport(TransferSupport supp) {
            if (supp.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return true;
            if (supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                return true;
            if (supp.isDataFlavorSupported(uriFlavor)) {
                return true;
            return false;
        private boolean importFiles(TransferSupport supp, File[] files) {
         // function that recursively processes all files and folders
        @Override
        public boolean importData(TransferSupport supp) {
            if (!canImport(supp)) {
                return false;
            String fns = "";
            Transferable t = supp.getTransferable();
            try {
                if (supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    File[] fnsl = (File[]) ((List) t.getTransferData(DataFlavor.javaFileListFlavor)).toArray();
                    return importFiles(supp, fnsl);
                } else if (supp.isDataFlavorSupported(uriFlavor)) {
                    String s = (String)t.getTransferData(uriFlavor);
              StringTokenizer st = new StringTokenizer(s, System.getProperty("line.separator"));
              ArrayList files = new ArrayList<File>();
              while (st.hasMoreTokens()) {
                   String file = st.nextToken();
                   try {
                           URL url = new URL(file);
                        files.add(new File(URLDecoder.decode(url.getPath())));
                   } catch (MalformedURLException mue) {
                    return importFiles(supp, (File []) files.toArray());
                } else {
                    fns = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException ex) {
                Logger.getLogger(CDrag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(CDrag.class.getName()).log(Level.SEVERE, null, ex);
         // the rest of the code here process a StringSelection
            return true;
        private List<File> dndData;
        private String relPath;
        private DataFlavor uriFlavor;
    }I have the following information available in the FileNode class - the name of the file, the path inside the application, date modified, size, whether it is a file or folder. How do I get these values into a javaFileListFlavor that Windows will understand? Also, I would need a way of returning the actual file data (which will be read from a remote server). The basic File class doesn't allow many of these things to be set.
    Regards
    Lionel

    I have the following information available in the FileNode class - the name of the file, the path inside the application, date modified, size, whether it is a file or folder. How do I get these values into a javaFileListFlavor that Windows will understand? Also, I would need a way of returning the actual file data (which will be read from a remote server). The basic File class doesn't allow many of these things to be set.I know I tried the same thing - I'm not sure this can be done at all, it could be that this can't be done if the file doesn't already exist somewhere on the local file system.
    Edited by: tjacobs01 on Feb 11, 2009 12:41 AM

  • 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.

  • Drag and Drop between Jlists

    Hello,
    I have two JLists, one containing music tracks (not actual tracks, just info like name, artist duration etc), and the other is a Playlist.
    So I want to be able to drag items from the database of tracks (Jlist one) to the playlist (Jlist two).
    I have looked how this is done and here is some of the code that I have:
        //allow the mouse to drag and drop tracks
        private class DragMouseAdapter extends MouseAdapter {
            public void mousePressed(MouseEvent e) {
                JComponent c = (JComponent)e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.COPY);
            //allow tracks to be dragged and dropped
            lstDatabase.setDragEnabled(true);
            MouseListener listener = new DragMouseAdapter();
            lstDatabase.addMouseListener(listener);
            //allow tracks to be dragged and dropped
            lstPlayList.addMouseListener(listener);
            lstPlayList.setTransferHandler(new TransferHandler("text"));Nothing seems to happen
    Any Ideas?
    Cheers

    The swing tutorial on "How to Use Drag and Drop" has a working example using JLists:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html#complex

  • Drag and drop panel

    I plan on writing a "drag and drop" interface that lets a user place things on a "canvas" and move them around. I will then let the user connect them with lines. Such things could be nodes in a network, one of the ideas I've had for using it. Basically this will allow visualization of whatever is happening behind the scenes, such as routing algorithms (etc).
    My plan at the moment is to have a canvas class and a can-be-placed-on-canvas class. The canvas object is in charge of handling the mouseclicks and moving of the objects. It will have an add() method which lets you add the objects to visualize, probably storing them in a collection.
    The objects placed on the canvas will have some form of .draw() method that returns what should be drawn to visualize them. I'd like to separate this away from the canvas so that different objects can be drawn.
    The problem I'm having at the moment is the actual dragging and dropping of the items. I could iterate over every object and see if it appears where the user is clicking, perhaps by comparing object.left + object.width and object.top + object.top to see if it encompasses the cursor. Surely this will be slow though and I'm not sure it would be the most efficient way of doing it.
    Another problem is z-order, I could assume that items are drawn according to their position in the collection. Then, when checking where a user clicks, iterate over the collection backwards as the item "on top" will be the first one found when going in the backward direction.
    I am presuming I will use a Graphics2D as the canvas, encompassed in a JComponent with an overridden .paint(). However, if this isn't the best way any other ideas would be nice.
    Before I start coding, does anybody have any ideas how I could design this if my suggestions do not make sense? Or are there are any significant flaws in the way I plan to do it?
    Thanks.

    So you are suggesting I use JComponent (which makes
    sense) and add a listener to it? That listener could
    probably be the canvas, which would then handle the
    dragging and dropping. I could also override paint()
    (including calling super.paint(), as I've found I have
    to do from past experience) in order to give my
    components the look I want.Yeh, Something like that. Everything you want to draw on your Canvas should be derived from JComponent
    (perhaps even JButton (depends on what you want to do)). The listener can be the JCanvas or perhaps
    a set of seperate behaviour classes that implement dragging (and optionally other behaviours such as
    context sensitive popup menus). Or you could have multiple listeners for different aspects of the behaviour
    Thanks for your suggestions, I guess the only
    difficulty now would be implementing the moving. Any
    ideas how the moving could be done?Make a single mouseListener. Register it with all the JComponents and listen for the MouseEvent.MOUSE_DRAGGED Event. When this occurs you obtain the Source of the event and change
    its coordinates (using setLocation or reshape)
    matfud

Maybe you are looking for

  • Missing Waveform Monitors - New Install, Most Recent Premiere CC 2014

    Hi, I recently downloaded and installed Premiere Pro CC and related apps with a cloud subscription on a new Mac Pro tower. I connected by working RAIDs and opened a PPro project originated on my previous edit system, an iMac.  Right away I noticed so

  • Lumia 1020 - Disable Post Processing?

    Preface:  I've only had the Lumia 1020 for 48 hours. Problem:  I've noticed that when taking pictures with the Nokia Pro Camera application, the preview after capturing the image is awesome.  If I then go to look at the captured image, there is a sho

  • From G5 to MacBook -- Transferring film sequence -- Best method?

    What is the best procedure for transferring a sequence onto the desktop of a MacBook Pro? (The MacBook doesn't have FCP loaded.) G5 Mac OS X (10.4.5) fcp 5.1.2 G5 Mac OS X (10.0.x) G5   Mac OS X (10.0.x)   G5   Mac OS X (10.0.x)  

  • What is better HDMI audio or Optical audio?

    Just wondering. If optical is better, will the optical port cancel out the HDMI Audio?

  • All I need is actionscript for a MovieClip

    I just need actionscript that then you rollover a movie clip it plays and when you roll off the Movieclip plays in reverse. I have provided a fla file for convience. http://www.geocities.com/demetriusmcclain/