如何在 Java 应用程序中添加文件浏览器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/796743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:36:19  来源:igfitidea点击:

How do I add a file browser inside my Java application?

javaswingjfilechooserfile-handling

提问by ranendra

I am new to Java progamming and am building a application that will add, display and remove files from a given folder location.

我是 Java 编程新手,正在构建一个应用程序,该应用程序将从给定的文件夹位置添加、显示和删除文件。

I have added files using JFileChooser and know how to delete the files. However I am stuck with the display portion.

我已经使用 JFileChooser 添加了文件并且知道如何删除这些文件。但是我被困在显示部分。

I want to display the files and folder using different icon inside my application. I tried to add a JFileChooser inside the display panel and disable the button and menu components of the dialog box, but I have not succeeded. Is there any better way to do this?

我想在我的应用程序中使用不同的图标显示文件和文件夹。我尝试在显示面板内添加一个JFileChooser,并禁用对话框的按钮和菜单组件,但没有成功。有没有更好的方法来做到这一点?

回答by jjnguy

I prefer the following way.

我更喜欢以下方式。

JFileChooser chooser= new JFileChooser();

int choice = choose.showOpenDialog();

if (choice != JFileChooser.APPROVE_OPTION) return;

File chosenFile = chooser.getSelectedFile();

// You can then do whatever you want with the file.

Calling this code will cause a JFileChooserto popup in its own window.

调用此代码将导致JFileChooser在其自己的窗口中弹出。

I usually call it from within a JButton's ActionListenercode.

我通常从 aJButtonActionListener代码中调用它。

fileChooseButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){

        // File chooser code goes here usually
    }
});

回答by Sam Barnum

If you don't need all the flexibility of JFileChooser, you should use java.awt.FileDialoginstead. Your OS X users will thank you. FileDialoguses a native file chooser window, while JFileChooseris a swing component, and lacks keyboard shortcuts and other niceties.

如果您不需要 的所有灵活性JFileChooser,则应java.awt.FileDialog改用。您的 OS X 用户会感谢您。 FileDialog使用本机文件选择器窗口,同时JFileChooser是一个摆动组件,并且缺少键盘快捷键和其他细节。

回答by willcodejavaforfood

I've never fully replicated a file browser. I have displayed files in list/tables using the icon that is provided by your platform. This is rather easy to do with the help of FileSystemView. Use the getSystemIcon(File) method to retrieve the correct icon. Then you can build a JList/JTable of files using this icon.

我从未完全复制文件浏览器。我已使用您的平台提供的图标在列表/表格中显示文件。在FileSystemView的帮助下,这很容易做到。使用 getSystemIcon(File) 方法来检索正确的图标。然后您可以使用此图标构建文件的 JList/JTable。