繁体   English   中英

如何将文件拖放到 JTable 中?

[英]How do I drag & drop files into a JTable?

我想将外部文件(例如从 windows 资源管理器)拖放到 JTable 中。 有人有一些示例代码来说明这是如何完成的吗?

只需使用 DropTarget class 即可接收丢弃事件。 您可以区分拖放到当前表(可用列/行)和滚动窗格(例如添加新行)

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 您需要在方法中添加以下代码:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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