How to open files in Java Swing without JFileChooser

落花浮王杯 提交于 2019-12-09 03:20:33

问题


I'm using Java Swing (GUI) and I want to add a button to my project for opening files.

I don't like the JFileChooser since it opens a small window for browsing through the files of the directories. Can I use something else instead of the JFileChooser under Java Swing?

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?

Here is the example of Java Swing with JFileChooser and I'm looking for something like this to put in my JFrame.


回答1:


JFileChooser with the native PLAF seems to fulfill the stated requirement.

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?

It is generally not a good idea to mix Swing/AWT/SWT components in the same top-level container. It is not a problem to open an AWT FileDialog over a Swing based JFrame since they are both top-level containers. I am pretty sure the same would apply to Swing/SWT or AWT/SWT.




回答2:


If you do not need the flexibility of the JFileChooser, you can opt for the FileDialog which uses the native OS file dialog. See also Code ranch topic and this answer on SO



来源:https://stackoverflow.com/questions/10900696/how-to-open-files-in-java-swing-without-jfilechooser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!