pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

將文件從操作系統拖放到 JTable java

drag and drop files from OS into JTable java(將文件從操作系統拖放到 JTable java)
本文介紹了將文件從操作系統拖放到 JTable java的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

誰能告訴我我做錯了什么?我可以使用常規面板進行拖放操作,但現在嘗試使用表格,但無法對其進行整理.我對 Points 和 DropTargets 感到困惑.不要介意添加"按鈕.我覺得我需要先處理 DnD.

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.

你的 drop 方法有點古怪...

Your drop method is a little queezy...

這是個壞主意……

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

您的放置代碼通常并不真正關心放置發生在哪一列,因為您已經有名稱和大小列,所以我實際上完全忽略了這一點.

Your 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 doesn't drop on an existing one or you reject the attempt.

(或拒絕不調用現有行的拖動)

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

要在用戶拖動時拒絕操作,你需要重寫 dragOver 方法...

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

在你的 drop 方法中,我還會做一些額外的檢查......

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

接受 Drag 的表外"

這個過程相對來說是一樣的,除了現在我們可以拋棄那些原本會導致我們拒絕拖放的條件(顯然)

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

還有drop方法

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

測試代碼

這是我用來測試代碼的完整運行示例...

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

這篇關于將文件從操作系統拖放到 JTable java的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期時間,就像在 UTC 中一樣)
How to convert Gregorian string to Gregorian Calendar?(如何將公歷字符串轉換為公歷?)
Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日歷到日期轉換.公歷到儒略歷切換)
java Calendar setFirstDayOfWeek not working(java日歷setFirstDayOfWeek不起作用)
Java: getting current Day of the Week value(Java:獲取當前星期幾的值)
主站蜘蛛池模板: 成人纸尿裤,成人尿不湿,成人护理垫-山东康舜日用品有限公司 | 广州番禺搬家公司_天河黄埔搬家公司_企业工厂搬迁_日式搬家_广州搬家公司_厚道搬迁搬家公司 | 软瓷_柔性面砖_软瓷砖_柔性石材_MCM软瓷厂家_湖北博悦佳软瓷 | 新密高铝耐火砖,轻质保温砖价格,浇注料厂家直销-郑州荣盛窑炉耐火材料有限公司 | 广州市哲铭油墨涂料有限公司,水性漆生产研发基地 | 3A别墅漆/3A环保漆_广东美涂士建材股份有限公司【官网】 | 云南成考网_云南成人高考报名网 粤丰硕水性环氧地坪漆-防静电自流平厂家-环保地坪涂料代理 | 无锡网站建设-做网站-建网站-网页设计制作-阿凡达建站公司 | 京马网,京马建站,网站定制,营销型网站建设,东莞建站,东莞网站建设-首页-京马网 | 挤塑板-XPS挤塑板-挤塑板设备厂家[襄阳欧格]| 苹果售后维修点查询,苹果iPhone授权售后维修服务中心 – 修果网 拼装地板,悬浮地板厂家,悬浮式拼装运动地板-石家庄博超地板科技有限公司 | 螺杆真空泵_耐腐蚀螺杆真空泵_水环真空泵_真空机组_烟台真空泵-烟台斯凯威真空 | 电竞馆加盟,沈阳网吧加盟费用选择嘉棋电竞_售后服务一体化 | 干式变压器厂_干式变压器厂家_scb11/scb13/scb10/scb14/scb18干式变压器生产厂家-山东科锐变压器有限公司 | 铝合金重力铸造_铝合金翻砂铸造_铝铸件厂家-东莞市铝得旺五金制品有限公司 | 桥架-槽式电缆桥架-镀锌桥架-托盘式桥架 - 上海亮族电缆桥架制造有限公司 | 盘煤仪,盘料仪,盘点仪,堆料测量仪,便携式激光盘煤仪-中科航宇(北京)自动化工程技术有限公司 | 工业洗衣机_工业洗涤设备_上海力净工业洗衣机厂家-洗涤设备首页 bkzzy在职研究生网 - 在职研究生招生信息咨询平台 | 合肥废气治理设备_安徽除尘设备_工业废气处理设备厂家-盈凯环保 合肥防火门窗/隔断_合肥防火卷帘门厂家_安徽耐火窗_良万消防设备有限公司 | 河北中仪伟创试验仪器有限公司是专业生产沥青,土工,水泥,混凝土等试验仪器的厂家,咨询电话:13373070969 | 合肥网带炉_安徽箱式炉_钟罩炉-合肥品炙装备科技有限公司 | 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 船老大板材_浙江船老大全屋定制_船老大官网| 成都租车_成都租车公司_成都租车网_众行宝 | 山东活动策划|济南活动公司|济南公关活动策划-济南锐嘉广告有限公司 | 水冷式工业冷水机组_风冷式工业冷水机_水冷螺杆冷冻机组-深圳市普威机械设备有限公司 | 水质监测站_水质在线分析仪_水质自动监测系统_多参数水质在线监测仪_水质传感器-山东万象环境科技有限公司 | 山东集装箱活动房|济南集装箱活动房-济南利森集装箱有限公司 | 深圳富泰鑫五金_五金冲压件加工_五金配件加工_精密零件加工厂 | 定制/定做衬衫厂家/公司-衬衫订做/订制价格/费用-北京圣达信 | 天一线缆邯郸有限公司_煤矿用电缆厂家_矿用光缆厂家_矿用控制电缆_矿用通信电缆-天一线缆邯郸有限公司 | 大通天成企业资质代办_承装修试电力设施许可证_增值电信业务经营许可证_无人机运营合格证_广播电视节目制作许可证 | 保定市泰宏机械制造厂-河北铸件厂-铸造厂-铸件加工-河北大件加工 | 耐火砖厂家,异形耐火砖-山东瑞耐耐火材料厂 | 济南电缆桥架|山东桥架-济南航丰实业有限公司 | 南京租车,南京汽车租赁,南京包车,南京会议租车-南京七熹租车 | 环压强度试验机-拉链拉力试验机-上海倾技仪器仪表科技有限公司 | 质检报告_CE认证_FCC认证_SRRC认证_PSE认证_第三方检测机构-深圳市环测威检测技术有限公司 | 上海洗地机-洗地机厂家-全自动洗地机-手推式洗地机-上海滢皓洗地机 | 乐之康护 - 专业护工服务平台,提供医院陪护-居家照护-居家康复 | 高精度-恒温冷水机-螺杆式冰水机-蒸发冷冷水机-北京蓝海神骏科技有限公司 |