我如何拖动;将文件拖放到JTable中?

时间:2009-04-02 09:32:59

标签: java

我想将外部文件(例如从Windows资源管理器)拖放到JTable中。任何人都有一些示例代码,如何做到这一点?

2 个答案:

答案 0 :(得分:11)

只需使用DropTarget类接收drop事件。您可以将drop分为当前表(可用列/行)和滚动窗格(例如添加新行)

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();
    }
}

答案 1 :(得分:7)

@yossale您需要将以下代码添加到方法中:

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);
  }

代替设置,您可以在验证数据不重复时将行附加到表中,并将文件信息作为新行添加到表中。