I'd like to drag and drop external files (e.g. from windows explorer) into a JTable. Anybody got some example code as how this is done?
How do I Drag and Drop? By default, if you left-click and HOLD the left mouse or touchpad button while moving your mouse pointer to a different folder location on the same drive, when you release the left mouse button the file will be moved to the new location where you released the mouse button.
Put the mouse pointer over the file or folder. Press and hold mouse button 1. Drag the icon to where you want to drop it. Release the mouse button.
"Clicking and dragging" is a way to move certain objects on the screen. To move an object, place the mouse cursor over it, press and hold down the left mouse button, then move the mouse while still holding down the left mouse button.
Simply use the DropTarget class to receive drop events. You can distinguish between drops into the current table (available columns/rows) and into the scroll pane (to e.g. add new rows)
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingTest extends JFrame{
private JTable table = new JTable();
private JScrollPane scroll = new JScrollPane(table);
private DefaultTableModel tm = new DefaultTableModel(new String[]{"a","b","c"},2);
public SwingTest() {
table.setModel(tm);
table.setDropTarget(new DropTarget(){
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
// handle drop inside current table
super.drop(dtde);
}
});
scroll.setDropTarget(new DropTarget(){
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
// handle drop outside current table (e.g. add row)
super.drop(dtde);
}
});
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(scroll);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
}
public static void main(String[] args) {
new SwingTest();
}
}
@yossale You need to add the following code to the method :
public synchronized void drop(DropTargetDropEvent dtde)
{
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = (List)t.getTransferData(DataFlavor.javaFileListFlavor);
File f = (File)fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column+1);
}
Instead of setting you can append rows to the table upon validating that data is not duplicate and add the file info as new rows to table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With