【问题标题】:How can I have a download file option in JAVA Swing?如何在 JAVA Swing 中有下载文件选项?
【发布时间】:2009-03-19 12:05:09
【问题描述】:

我是 Swing 新手,希望在我的 Swing 代码中实现下载文件功能,这将允许用户保存或打开特定文件。

我确实看过 JFileChooser.showOpenDialog 和 showSaveDialog,但我不想使用它,因为它让我可以从文件系统中选择任何文件。

希望我的问题很清楚。请帮我解决这个问题。

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您想使用它们,并添加一个过滤器。例如:

        JFileChooser chooser = new JFileChooser();
        // Note: source for ExampleFileFilter can be found in FileChooserDemo,
        // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
        ExampleFileFilter filter = new ExampleFileFilter();
        filter.addExtension("jpg");
        filter.setDescription("JPG & GIF Images");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(parent);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
           System.out.println("You chose to open this file: " +
                chooser.getSelectedFile().getName());
        }
    

    这只会显示 JPG 和 GIF 文件。从here窃取的示例

    编辑:你知道 ExampleFileFilter 实现了抽象类FileFilter

    编辑:由于您知道文件的名称,因此您可以只使用一个打开按钮并使用 Runtime.getRuntime.exec('the file to beopen.doc") 并且应该在适当的应用。

    为了保存,您仍然需要提示他们找出他们想要保存它的位置,因此您仍然需要 JFileChooser。我仍然会使用过滤器,并在必要时动态确定文件扩展名,然后执行:

        JFileChooser chooser = new JFileChooser();
        // Note: source for ExampleFileFilter can be found in FileChooserDemo,
        // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
        
        String selectedFile = "The suggested save name.";
        chooser.setSelectedFile(selectedFile);
    
        ExampleFileFilter filter = new ExampleFileFilter();
        String extension = "Do something to find your extension";
        filter.addExtension(extension);
        filter.setDescription("JPG & GIF Images");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(parent);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
           System.out.println("You chose to open this file: " +
                chooser.getSelectedFile().getName());
           //then write your code to write to disk
        }
    

    希望对您有所帮助。

    【讨论】:

    • 嘿,我不想限制打开文件,但希望有一个对话框允许用户打开或保存特定文件,比如我的系统生成的报告.希望现在很清楚了。
    • 您是说希望能够提示他们打开您已经知道其名称的特定文件吗?
    • 是的,你绝对是 rit..我想要的是,如果我们在 gmail 上有附件,它会提示下载,然后显示保存或打开。
    • 嘿谢谢..没试过..但我认为这对我来说很好:)
    【解决方案2】:

    您可以将过滤器添加到文件选择器。很容易实现你自己的,它只接受你允许的文件。

    选择文件后,您需要自己实现文件的保存/读取。桌面应用程序中没有下载/上传之类的东西。

    【讨论】:

    • 据我了解,过滤器 wud 只是帮助我限制某些文件类型。我想要的是一个对话框,它允许用户打开由我的工具生成的特定文件,比如报告或 smthing。
    • Thnaks Marko.. 现在我知道该怎么做了.. 非常感谢您的意见:)
    猜你喜欢
    • 2020-03-31
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多