将文件从OS拖放到JTable java中 [英] drag and drop files from OS into JTable java

查看:128
本文介绍了将文件从OS拖放到JTable java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我我做错了什么?我能够使用常规面板进行拖放操作,但现在正在尝试使用表格,我无法将其排除。我对点和DropTargets感到困惑。不要介意添加按钮。我觉得我需要先处理DnD。

  public class Table extends JFrame implements ActionListener {

私人JTable表;
私人JScrollPane滚动;
私人JButton添加;
私人JFileChooser选择;
私人JMenuBar菜单栏;
私人JMenu菜单;
私有JMenuItem文件;
private DefaultTableModel tm = new DefaultTableModel(new String [] {File,
File Type,Size,Status},2);

public Table(){

// String column [] = {Filename,File Type,Size,Status};
/ *
* Object [] [] data = {{File1,.jpg,32 MB,未处理},
* {File2 .txt,5 Kb,未处理},{File3,.doc,3 Kb,
*未处理},
*};
* /

table = new JTable();
table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500,300));

scroll = new JScrollPane(table);

table.setDropTarget(new DropTarget(){
@Override
public synchronized void drop(DropTargetDropEvent dtde){

点点= dtde.getLocation ();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);

dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
可传递t = dtde.getTransferable();
列表fileList = null;
try {
fileList =(List)t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch(UnsupportedFlavorException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO Auto -generated catch块
e.printStackTrace();
}
文件f =(File)fileList.get(0);
table.setValueAt(f.getAbsolutePath(),row,column);
table.setValueAt(f.length(),row,column + 1);
super.drop(dtde);
}
});
scroll.setDropTarget(new DropTarget(){
@Override
public synchronized void drop(DropTargetDropEvent dtde){
点点= dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);

dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
可传递t = dtde.getTransferable ();
列表fileList = null;
尝试{
fileList =(List)t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch(UnsupportedFlavorException e) {
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
文件f =(File)fileList.get(0);
table.setValueAt(f.getAbsolutePath(),row,column);
table.setValueAt(f.length(),row,column + 1);
// handle drop current current table(例如添加行)
super.drop(dtde);
}
});

add(scroll,BorderLayout.CENTER);

menubar = new JMenuBar();
menu = new JMenu(File);
file = new JMenuItem(file);
menu.add(file);
// menubar.add(menu);
add(menu,BorderLayout.NORTH);

ImageIcon icon = new ImageIcon(lock_icon.png);

add = new JButton(Add,图标);
add.addActionListener(this);

JFileChooser choose = new JFileChooser();
choose.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e){
JButton clicked =(JButton)e.getSource();

int returnValue = 0;

if(clicked == add){
choose = new JFileChooser();
choose.showOpenDialog(null);

if(returnValue == JFileChooser.APPROVE_OPTION){
文件文件= choose.getSelectedFile();
file.getAbsolutePath();

}

}

}

public static void main(String [] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){

Table t = new Table();

t.setDefaultCloseOperation (EXIT_ON_CLOSE);
t.pack();
t.setSize(600,200);
t.setVisible(true);
t.setTitle(ZipLock) ;
t.setIconImage(null);

}
});

}

}


解决方案

我个人将在滚动窗格上拖放放置目标,这将导致您遇到许多问题。



您的放下方法是一个小小的queezy ...



这是一个坏主意....

 列表fileList = null; 
try {
fileList =(List)t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch(UnsupportedFlavorException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
文件f =(File)fileList.get(0);
table.setValueAt(f.getAbsolutePath(),row,column);
table.setValueAt(f.length(),row,column + 1);

基本上,您可以尝试从可传递的文件列表中提取文件列表,无论操作是否成功,你尝试使用它吗?你根本没有验证返回的值...



你的删除代码一般不太在乎什么列,发生在你的已经有名字和大小的列,所以我实际上完全忽略了。



对于这一行,现在你有两个选择。当用户没有删除现有的行或您拒绝尝试时,您可以添加新行。



拒绝拖动表



(或拒绝不调用现有行的拖动)



要拒绝用户拖动时的操作,您需要覆盖 dragOver 方法...

  @Override 
public synchronized void dragOver(DropTargetDragEvent dtde){
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if(row< 0){
dtde.rejectDrag();
table.clearSelection();
} else {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
table.setRowSelectionInterval(row,row);
}
}

现在,我开始有点聪明而不是以聪明的方式)。基本上,如果用户拖动了一行,我已经突出显示了。这使得它更明显地在哪里下降。



在你的下拉方法中,我还会做一些额外的检查...

  @Override 
public synchronized void drop(DropTargetDropEvent dtde){
点点= dtde.getLocation();
int row = table.rowAtPoint(point);
if(row> = 0){
if(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
可转移t = dtde.getTransferable();
列表fileList = null;
try {
fileList =(List)t.getTransferData(DataFlavor.javaFileListFlavor);
if(fileList.size()> 0){
table.clearSelection();
点点= dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model =(DefaultTableModel)table.getModel();
model.setValueAt(f.getAbsolutePath(),row,0);
model.setValueAt(f.length(),row,2);
}
} catch(UnsupportedFlavorException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}



接受Drag的外部表



这个过程是相同的,除了现在我们可以丢弃否则会导致使用拒绝拖放的条件(显然)

  @Override 
public synchronized void dragOver(DropTargetDragEvent dtde){
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if(row< 0){
table.clearSelection();
} else {
table.setRowSelectionInterval(row,row);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}

drop 方法

  @Override 
public synchronized void drop(DropTargetDropEvent dtde){
if(dtde.isDataFlavorSupported DataFlavor.javaFileListFlavor)){
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
可转移t = dtde.getTransferable();
列表fileList = null;
try {
fileList =(List)t.getTransferData(DataFlavor.javaFileListFlavor);
if(fileList.size()> 0){
table.clearSelection();
点点= dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model =(DefaultTableModel)table.getModel();
for(Object value:fileList){
if(value instanceof File){
File f =(File)value;
if(row< 0){
System.out.println(addRow);
model.addRow(new Object [] {f.getAbsolutePath(),,f.length(),,});
} else {
System.out.println(insertRow+ row);
model.insertRow(row,new Object [] {f.getAbsolutePath(),,f.length(),,});
row ++;
}
}
}
}
} catch(UnsupportedFlavorException e){
// TODO自动生成的catch块
e.printStackTrace ();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}

注意。这将在放置点插入行,将所有现有的行向下推或如果没有删除现有行,将会将它们添加到最后。



测试代码



这是一个完整的运行示例,我用来测试代码...

  public class DropTable {

public static void main(String [] args){
new DropTable();
}

public DropTable(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
尝试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){
}

JFrame框架= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

});
}

public class DropPane扩展JPanel {

private JTable table;
私人JScrollPane滚动;
private DefaultTableModel tm = new DefaultTableModel(new String [] {File,File Type,Size,Status},0);

public DropPane(){
table = new JTable();
table.setShowGrid(true);
table.setShowHorizo​​ntalLines(true);
table.setShowVerticalLines(true);
table.setGridColor(Color.GRAY);

table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500,300));

scroll = new JScrollPane(table);

table.setDropTarget(new DropTarget(){
@Override
public synchronized void dragOver(DropTargetDragEvent dtde){
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if(row< 0){
table.clearSelection();
} else {
table.setRowSelectionInterval行,行);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}

@Override
public synchronized void drop(DropTargetDropEvent dtde) {
if(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
可传递t = dtde.getTransferable();
列表fileList = null;
try {
fileList =(List)t.getTransferData(DataFlavor.javaFileListFlavor);
if(fileList.size()> 0){
table.clearSelection();
点点= dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model =(DefaultTableModel)table.getModel();
for(Object value:fileList){
if(value instanceof File){
File f =(File)value;
if(row< 0){
model.addRow(new Object [] {f.getAbsolutePath(),,f.length(),,})
} else {
model.insertRow(row,new Object [] {f.getAbsolutePath(),,f.length(),,});
row ++;
}
}
}
}
} catch(UnsupportedFlavorException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}

});

add(scroll,BorderLayout.CENTER);
}
}
}


Can someone show me what I'm doing wrong? I was able to get drag and drop working with a regular panel but now trying with a table and I can't sort it out. I'm getting confused with the Points and DropTargets. Dont mind the "Add" button. I feel like I need to deal with the DnD first.

public class Table extends JFrame implements ActionListener {

    private JTable table;
    private JScrollPane scroll;
    private JButton add;
    private JFileChooser choose;
    private JMenuBar menubar;
    private JMenu menu;
    private JMenuItem file;
    private DefaultTableModel tm = new DefaultTableModel(new String[] { "File",
            "File Type", "Size", "Status" }, 2);

    public Table() {

        // String column [] = {"Filename ","File Type", "Size", "Status" };
        /*
         * Object[][] data = { {"File1", ".jpg","32 MB", "Not Processed"},
         * {"File2", ".txt"," 5 Kb", "Not Processed"}, {"File3", ".doc","3 Kb",
         * "Not Processed"},
         * };
         */

        table = new JTable();
        table.setModel(tm);
        table.setFillsViewportHeight(true);
        table.setPreferredSize(new Dimension(500, 300));

        scroll = new JScrollPane(table);

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

                dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                Transferable t = dtde.getTransferable();
                List fileList = null;
                try {
                    fileList = (List) t
                            .getTransferData(DataFlavor.javaFileListFlavor);
                } catch (UnsupportedFlavorException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                File f = (File) fileList.get(0);
                table.setValueAt(f.getAbsolutePath(), row, column);
                table.setValueAt(f.length(), row, column + 1);
                super.drop(dtde);
            }
        });
        scroll.setDropTarget(new DropTarget() {
            @Override
            public synchronized void drop(DropTargetDropEvent dtde) {
                Point point = dtde.getLocation();
                int column = table.columnAtPoint(point);
                int row = table.rowAtPoint(point);

                dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                Transferable t = dtde.getTransferable();
                List fileList = null;
                try {
                    fileList = (List) t
                            .getTransferData(DataFlavor.javaFileListFlavor);
                } catch (UnsupportedFlavorException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                File f = (File) fileList.get(0);
                table.setValueAt(f.getAbsolutePath(), row, column);
                table.setValueAt(f.length(), row, column + 1);
                // handle drop outside current table (e.g. add row)
                super.drop(dtde);
            }
        });

        add(scroll, BorderLayout.CENTER);

        menubar = new JMenuBar();
        menu = new JMenu("File");
        file = new JMenuItem("file");
        menu.add(file);
        // menubar.add(menu);
        add(menu, BorderLayout.NORTH);

        ImageIcon icon = new ImageIcon("lock_icon.png");

        add = new JButton("Add", icon);
        add.addActionListener(this);

        JFileChooser choose = new JFileChooser();
        choose.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton) e.getSource();

        int returnValue = 0;

        if (clicked == add) {
            choose = new JFileChooser();
            choose.showOpenDialog(null);

            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File file = choose.getSelectedFile();
                file.getAbsolutePath();

            }

        }

    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                Table t = new Table();

                t.setDefaultCloseOperation(EXIT_ON_CLOSE);
                t.pack();
                t.setSize(600, 200);
                t.setVisible(true);
                t.setTitle("ZipLock");
                t.setIconImage(null);

            }
        });

    }

}

解决方案

I personally would ditch the drop target on the scroll pane, it's going to cause you to many problems.

Your drop method is a little queezy...

This is a bad idea....

List fileList = null;
try {
    fileList = (List) t
        .getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);

Basically, you try and extract the file list from the transferable and regardless of the success of the operation, you try and use it ?! You do no validation of the returned value at all...

You're drop code generally doesn't really care about what column the drop occurred on, as you have name and size columns already, so I'd actually ignore that altogether.

As for the row, now you have two choices. Either you add a new row when the user does not drop on an existing one or you reject the attempt.

Reject drag's "outside" of table

(Or reject drags that don't call over an existing row)

To reject the operation while the user is dragging, you need to override the dragOver method...

@Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
    Point point = dtde.getLocation();
    int row = table.rowAtPoint(point);
    if (row < 0) {
        dtde.rejectDrag();
        table.clearSelection();
    } else {
        dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
        table.setRowSelectionInterval(row, row);
    }
}

Now, I'm begin a little smart here (and not in the clever way). Basically, if the user has dragged over a row, I've highlighted it. This makes it a little more obvious where the drop is going.

In your drop method, I would also make some additional checks...

@Override
public synchronized void drop(DropTargetDropEvent dtde) {    
    Point point = dtde.getLocation();
    int row = table.rowAtPoint(point);
    if (row >= 0) {
        if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            Transferable t = dtde.getTransferable();
            List fileList = null;
            try {
                fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                if (fileList.size() > 0) {
                    table.clearSelection();
                    Point point = dtde.getLocation();
                    int row = table.rowAtPoint(point);
                    DefaultTableModel model = (DefaultTableModel) table.getModel();
                    model.setValueAt(f.getAbsolutePath(), row, 0);
                    model.setValueAt(f.length(), row, 2);
                }
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            dtde.rejectDrop();
        }
    } else {
        dtde.rejectDrop();
    }
}

Accept Drag's "outside" of the table

The process is relativly the same, except now we can throw away the conditions that would have otherwise caused use to reject the drag/drop (obviously)

@Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
    Point point = dtde.getLocation();
    int row = table.rowAtPoint(point);
    if (row < 0) {
        table.clearSelection();
    } else {
        table.setRowSelectionInterval(row, row);
    }
    dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}

And the drop method

@Override
public synchronized void drop(DropTargetDropEvent dtde) {    
    if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
        Transferable t = dtde.getTransferable();
        List fileList = null;
        try {
            fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
            if (fileList.size() > 0) {
                table.clearSelection();
                Point point = dtde.getLocation();
                int row = table.rowAtPoint(point);
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                for (Object value : fileList) {
                    if (value instanceof File) {
                        File f = (File) value;
                        if (row < 0) {
                            System.out.println("addRow");
                            model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                        } else {
                            System.out.println("insertRow " + row);
                            model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                            row++;
                        }
                    }
                }
            }
        } catch (UnsupportedFlavorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        dtde.rejectDrop();
    }
}

Note. This will insert rows at the drop point, push all the existing rows down OR if not dropped on an existing row, will add them to the end...

TEST CODE

This a full running example I used to test the code...

public class DropTable {

    public static void main(String[] args) {
        new DropTable();
    }

    public DropTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new DropPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class DropPane extends JPanel {

        private JTable table;
        private JScrollPane scroll;
        private DefaultTableModel tm = new DefaultTableModel(new String[]{"File", "File Type", "Size", "Status"}, 0);

        public DropPane() {
            table = new JTable();
            table.setShowGrid(true);
            table.setShowHorizontalLines(true);
            table.setShowVerticalLines(true);
            table.setGridColor(Color.GRAY);

            table.setModel(tm);
            table.setFillsViewportHeight(true);
            table.setPreferredSize(new Dimension(500, 300));

            scroll = new JScrollPane(table);

            table.setDropTarget(new DropTarget() {
                @Override
                public synchronized void dragOver(DropTargetDragEvent dtde) {
                    Point point = dtde.getLocation();
                    int row = table.rowAtPoint(point);
                    if (row < 0) {
                        table.clearSelection();
                    } else {
                        table.setRowSelectionInterval(row, row);
                    }
                    dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
                }

                @Override
                public synchronized void drop(DropTargetDropEvent dtde) {
                    if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                        Transferable t = dtde.getTransferable();
                        List fileList = null;
                        try {
                            fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                            if (fileList.size() > 0) {
                                table.clearSelection();
                                Point point = dtde.getLocation();
                                int row = table.rowAtPoint(point);
                                DefaultTableModel model = (DefaultTableModel) table.getModel();
                                for (Object value : fileList) {
                                    if (value instanceof File) {
                                        File f = (File) value;
                                        if (row < 0) {
                                            model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                                        } else {
                                            model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                                            row++;
                                        }
                                    }
                                }
                            }
                        } catch (UnsupportedFlavorException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        dtde.rejectDrop();
                    }
                }

            });

            add(scroll, BorderLayout.CENTER);
        }
    }
}

这篇关于将文件从OS拖放到JTable java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆