简体   繁体   English

如何在没有JFileChooser的Java Swing中打开文件

[英]How to open files in Java Swing without JFileChooser

I'm using Java Swing (GUI) and I want to add a button to my project for opening files. 我正在使用Java Swing(GUI),我想在我的项目中添加一个按钮来打开文件。

I don't like the JFileChooser since it opens a small window for browsing through the files of the directories. 我不喜欢JFileChooser因为它打开了一个小窗口来浏览目录的文件。 Can I use something else instead of the JFileChooser under Java Swing ? 我可以在Java Swing下使用其他东西而不是JFileChooser吗?

I've tried to use elements of SWT but it didn't work, meaning is the use of the button object and then use it inside the JFrame , but that failed, so I guess SWT and Swing don't mix together? 我试图使用SWT的元素,但它不起作用,意思是使用按钮对象然后在JFrame使用它,但是失败了,所以我猜SWT和Swing不会混合在一起?

Here is the example of Java Swing with JFileChooser and I'm looking for something like this to put in my JFrame . 下面是该示例的Java Swing与JFileChooser中 ,我寻找的东西像这样把我的JFrame

Windows文件对话框

JFileChooser with the native PLAF seems to fulfill the stated requirement. 原生PLAF的JFileChooser似乎符合规定的要求。

原生PLAF文件选择器

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class NativeFileChooser {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch(Exception e) {
                    e.printStackTrace();
                }
                JFileChooser jfc = new JFileChooser();
                jfc.showOpenDialog(null);
            }
        });
    }
}

Still not quite to your liking? 仍然不太符合你的喜好? Then you might start with this one & change it to need: 然后你可以从这个开始并改变它需要:


..so I guess SWT and Swing don't mix together? ..所以我猜SWT和Swing不会混在一起?

It is generally not a good idea to mix Swing/AWT/SWT components in the same top-level container . 同一顶级容器中混合使用Swing / AWT / SWT组件通常不是一个好主意。 It is not a problem to open an AWT FileDialog over a Swing based JFrame since they are both top-level containers. 在基于Swing的JFrame上打开AWT FileDialog不是问题,因为它们都是顶级容器。 I am pretty sure the same would apply to Swing/SWT or AWT/SWT. 我很确定这同样适用于Swing / SWT或AWT / SWT。

If you do not need the flexibility of the JFileChooser , you can opt for the FileDialog which uses the native OS file dialog. 如果您不需要JFileChooser的灵活性,则可以选择使用本机OS文件对话框的FileDialog See also Code ranch topic and this answer on SO 另请参阅Code ranch主题SO上的这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM