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

將文件從操作系統拖放到 Java 應用程序 (Swing)

Drag#39;n drop files from the OS to Java application (Swing)(將文件從操作系統拖放到 Java 應用程序 (Swing))
本文介紹了將文件從操作系統拖放到 Java 應用程序 (Swing)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

首先讓我說我一直在閱讀 drag'n drop tutorial 和關于 SO 的類似問題,但不幸的是,我對這件事感到更加困惑.我想要實現的目標相對簡單,所以我很驚訝它已經給我帶來了這么多麻煩.我正在編寫一個小型實用程序應用程序,它將一堆結果文件(自定義的 xml 類型)合并到一個大的制表符分隔的文本文件中.大多數功能已經編碼,但是我想為它制作一個像樣的 GUI.

Let me start by saying that I have been reading the drag'n drop tutorial and similar questions asked on SO, but unfortunately I have only gotten more confused about this matter. What I want to achieve is relatively simple so I am surprised that it got me in so much trouble already. I am writing a small utility application which will consolidate a bunch of result files (custom defined xml-type) into a large tab-separated text file. Most of the functionality is already coded, however I wanted to make a decent GUI for it.

我想要的是能夠將文件拖放到組件中(例如 JTextArea)以一種很好的方式(閱讀:不是完整路徑,而是一個小圖標和名稱).我希望能夠提供一個 JFileChooser 來瀏覽文件.然后我將依次解析文件以生成我想要的矩陣.

What I want is to be able to drag'n drop files into a component (for instance JTextArea) in a nice and gracious way (read: not full paths, but instead a small icon and name). I would like to be able to supply a JFileChooser to browse for files as well. I will then parse the files sequentially to produce the matrix I want.

到目前為止,我了解到該框架已經存在,但是任何其他功能都需要自定義構建.我在 Netbeans 中創建了一個測試 GUI,并試圖將一堆文件拖到 JTextArea 上,但它們顯示為文件路徑,并且不可否認它看起來很丑陋.

What I have learned so far is that the framework is already there however any additional functionality needs to be custom built. I have created a test GUI in Netbeans and tried to drag a bunch of files onto a JTextArea, but they appear as file paths, and admittedly it looks very ugly.

我非常感謝有關如何以簡潔的方式解決(或澄清)此問題的任何提示和指導.請注意,我確實打算在多個不同的操作系統(Mac、Win 和 Linux)上使用該軟件.

I would really appreciate any tips and guidance on how to solve (or clarify) this problem in a neat way. Note that I do intend to use the software on multiple different OS (Mac,Win and Linux).

到目前為止,我的代碼基于 Sun 教程中的一個示例,如下所示

the code I have so far is based on one of the examples from Sun tutorials and is as follows

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    JFileChooser fc;
    JButton clear;
    JTextArea dropZone, console;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

  public ConsolidatorDemo() {
    super(new BorderLayout());

    fc = new JFileChooser();;
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);               


    JPanel fcPanel = new JPanel(new BorderLayout());
    fcPanel.add(fc, BorderLayout.CENTER);

    clear = new JButton("Clear All");
    clear.addActionListener(this);
    JPanel buttonPanel = new JPanel(new BorderLayout());
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    buttonPanel.add(clear, BorderLayout.LINE_END);

    JPanel leftUpperPanel = new JPanel(new BorderLayout());
    leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
    leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);


    JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
    leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    dropZone = new JTextArea();
    dropZone.setColumns(20);
    dropZone.setLineWrap(true);
    dropZone.setRows(5);
    dropZone.setDragEnabled(true);
    dropZone.setDropMode(javax.swing.DropMode.INSERT);
    dropZone.setBorder(new TitledBorder("Selected files/folders"));
    leftLowerPanel.setViewportView(dropZone);

    childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            leftUpperPanel, leftLowerPanel);
    childSplitPane.setDividerLocation(400);
    childSplitPane.setPreferredSize(new Dimension(480, 650));

    console = new JTextArea();
    console.setColumns(40);
    console.setLineWrap(true);
    console.setBorder(new TitledBorder("Console"));

    parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    childSplitPane, console);
    parentSplitPane.setDividerLocation(480);
    parentSplitPane.setPreferredSize(new Dimension(800, 650));

    add(parentSplitPane, BorderLayout.CENTER);

}

public void setDefaultButton() {
    getRootPane().setDefaultButton(clear);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clear) {
        dropZone.setText("");

    }
}

/**
 * Create the GUI and show it. For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    try {
      //UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    }catch (Exception e){
      e.printStackTrace();
    }

    //Create and set up the window.
    JFrame frame = new JFrame("Consolidator!");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    //Create and set up the menu bar and content pane.
    ConsolidatorDemo demo = new ConsolidatorDemo();
    demo.setOpaque(true); //content panes must be opaque
    frame.setContentPane(demo);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    demo.setDefaultButton();
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

推薦答案

這里有一個快速的片段,用于將實際的文件導入 JList(而不是將其字符串表示導入文本組件)并使用自定義渲染器來呈現它很好.它改編自 BasicDnD(在教程中):

here's a quick snippet to import the actual Files into a JList (as opposed to importing its String representation into a text component) and use a custom renderer to present it nicely. It's adapted from the BasicDnD (in the tutorial):

    fileDropper = new JList(new DefaultListModel());
    fileDropper.setDragEnabled(true);
    leftLowerPanel.setViewportView(fileDropper);

    TransferHandler handler =   new TransferHandler() {

        @Override
        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import FileList
            if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                return false;
            }
            return true;
        }

        @Override
        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for FileList flavor
            if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            // Get the fileList that is being dropped.
            Transferable t = info.getTransferable();
            List<File> data;
            try {
                data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
            } 
            catch (Exception e) { return false; }
            DefaultListModel model = (DefaultListModel) fileDropper.getModel();
            for (File file : data) {
                model.addElement(file);
            }
            return true;
        }

        private void displayDropLocation(String string) {
            System.out.println(string);
        }
    };
    fileDropper.setTransferHandler(handler);
    fileDropper.setCellRenderer(new DefaultListRenderer(
          StringValues.FILE_NAME, IconValues.FILE_ICON));

無法拒絕顯示 SwingX 渲染器配置 :-) 在核心 java 中,您可以手動完成,類似于

Couldn't resist to showing SwingX renderer config :-) In core java, you would do it manually, something like

   class MyRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(...) {
            super.getList...
            if (value instanceof File) {
                setText(FileSystemView.getFileSystemView().getDisplayName(value);
                setIcon(FileSystemView.getFileSystemView().getSystemIcon(value);
            } 
            return this;
        }

   }

這篇關于將文件從操作系統拖放到 Java 應用程序 (Swing)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持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:獲取當前星期幾的值)
主站蜘蛛池模板: 托盘租赁_塑料托盘租赁_托盘出租_栈板出租_青岛托盘租赁-优胜必达 | 北京乾茂兴业科技发展有限公司 | 贴板式电磁阀-不锈钢-气动上展式放料阀-上海弗雷西阀门有限公司 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 | 运动木地板厂家,篮球场木地板品牌,体育场馆木地板安装 - 欧氏运动地板 | AGV无人叉车_激光叉车AGV_仓储AGV小车_AGV无人搬运车-南昌IKV机器人有限公司[官网] | 北京自然绿环境科技发展有限公司专业生产【洗车机_加油站洗车机-全自动洗车机】 | Q361F全焊接球阀,200X减压稳压阀,ZJHP气动单座调节阀-上海戎钛 | 九州网址_专注于提供网址大全分享推广中文网站导航服务 | 乳化沥青设备_改性沥青设备_沥青加温罐_德州市昊通路桥工程有限公司 | 上海瑶恒实业有限公司|消防泵泵|离心泵|官网 | 私人别墅家庭影院系统_家庭影院音响_家庭影院装修设计公司-邦牛影音 | 巨野电机维修-水泵维修-巨野县飞宇机电维修有限公司 | 钢格板_钢格栅_格栅板_钢格栅板 - 安平县鑫拓钢格栅板厂家 | 合肥抖音SEO网站优化-网站建设-网络推广营销公司-百度爱采购-安徽企匠科技 | 电力测功机,电涡流测功机,磁粉制动器,南通远辰曳引机测试台 | 耐高温风管_耐高温软管_食品级软管_吸尘管_钢丝软管_卫生级软管_塑料波纹管-东莞市鑫翔宇软管有限公司 | 热镀锌槽钢|角钢|工字钢|圆钢|H型钢|扁钢|花纹板-天津千百顺钢铁贸易有限公司 | 欧景装饰设计工程有限公司-无锡欧景装饰官网 | 立式硫化罐-劳保用品硫化罐-厂家直销-山东鑫泰鑫硫化罐厂家 | 市政路灯_厂家-淄博信达电力科技有限公司 | 防弹玻璃厂家_防爆炸玻璃_电磁屏蔽玻璃-四川大硅特玻科技有限公司 | 合肥礼品公司-合肥礼品定制-商务礼品定制公司-安徽柏榽商贸有限公司 | TPM咨询,精益生产管理,5S,6S现场管理培训_华谋咨询公司 | 奇酷教育-Python培训|UI培训|WEB大前端培训|Unity3D培训|HTML5培训|人工智能培训|JAVA开发的教育品牌 | 铝机箱_铝外壳加工_铝外壳厂家_CNC散热器加工-惠州市铂源五金制品有限公司 | 济南网站建设|济南建网站|济南网站建设公司【济南腾飞网络】【荐】 | 托盘租赁_塑料托盘租赁_托盘出租_栈板出租_青岛托盘租赁-优胜必达 | 拉曼光谱仪_便携式|激光|显微共焦拉曼光谱仪-北京卓立汉光仪器有限公司 | 哈尔滨发电机,黑龙江柴油发电机组-北方星光 | 大型冰雕-景区冰雕展制作公司,3D创意设计源头厂家-[赛北冰雕] | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 【电子厂招聘_普工招工网_工厂招聘信息平台】-工立方打工网 | 云阳人才网_云阳招聘网_云阳人才市场_云阳人事人才网_云阳人家招聘网_云阳最新招聘信息 | 进口便携式天平,外校_十万分之一分析天平,奥豪斯工业台秤,V2000防水秤-重庆珂偌德科技有限公司(www.crdkj.com) | 无锡网站建设_企业网站定制-网站制作公司-阿凡达网络 | 马尔表面粗糙度仪-MAHR-T500Hommel-Mitutoyo粗糙度仪-笃挚仪器 | 小程序开发公司-小程序制作-微信小程序开发-小程序定制-咏熠软件 | 生物除臭剂-除味剂-植物-污水除臭剂厂家-携葵环保有限公司 | 石栏杆_青石栏杆_汉白玉栏杆_花岗岩栏杆 - 【石雕之乡】点石石雕石材厂 | 镀锌钢格栅_热镀锌格栅板_钢格栅板_热镀锌钢格板-安平县昊泽丝网制品有限公司 | 螺纹三通快插接头-弯通快插接头-宁波舜驰气动科技有限公司 |