简体   繁体   中英

How do I drag & drop files into a JTable?

I'd like to drag and drop external files (eg from windows explorer) into a JTable. Anybody got some example code as how this is done?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM