Does Swing support Windows 7-style file choosers?

ぃ、小莉子 提交于 2019-11-26 22:18:44

It does not appear this is supported in Swing in Java 6.

Currently, the simplest way I can find to open this dialog is through SWT, not Swing. SWT's FileDialog (javadoc) brings up this dialog. The following is a modification of SWT's FileDialog snippet to use an open instead of save dialog. I know this isn't exactly what you're looking for, but you could isolate this to a utility class and add swt.jar to your classpath for this functionality.

import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;

public class SWTFileOpenSnippet {
    public static void main (String [] args) {
        Display display = new Display ();
        Shell shell = new Shell (display);
        // Don't show the shell.
        //shell.open ();  
        FileDialog dialog = new FileDialog (shell, SWT.OPEN | SWT.MULTI);
        String [] filterNames = new String [] {"All Files (*)"};
        String [] filterExtensions = new String [] {"*"};
        String filterPath = "c:\\";
        dialog.setFilterNames (filterNames);
        dialog.setFilterExtensions (filterExtensions);
        dialog.setFilterPath (filterPath);
        dialog.open();
        System.out.println ("Selected files: ");
        String[] selectedFileNames = dialog.getFileNames();
        for(String fileName : selectedFileNames) {
            System.out.println("  " + fileName);
        }
        shell.close();
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
} 
Alexey Ivanov

Even native Windows applications can get this type of dialog displayed on Windows 7. This is usually controlled by flags in OPENFILENAME structure and its size passed in a call to WinAPI function GetOpenFileName. Swing (Java) uses hooks to get events from the Open File dialog; these events are passed differently between Windows XP and Windows 7 version.

So the answer is you can't control the look of FileChooser from Swing. However, when Java gets support for this new look, you'll get the new style automatically.

Another option is to use SWT, as suggested in this answer. Alternatively you can use JNA to call Windows API or write a native method to do this.

A bit of a hack, and slightly less empowered than the Swing version, but have you considered using a java.awt.FileDialog? It should not just look like the Windows file chooser, but actually be one.

I don't believe Swing would cover that though it may, if it doesn't you may need to look at something like SWT, which would make use of the actual native component, or do a custom UI element, like something out of the "Filthy Rich Clients" book.

Luke Usherwood

Java 8 may finally bring a solution to this, but unfortunately (for Swing apps) it comes only as the JavaFX class FileChooser:

I've tested this code from here and it indeed pops a modern dialog (Windows 7 here):

FileChooser fileChooser = new FileChooser();

//Set extension filter
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);

//Show open file dialog
File file = fileChooser.showOpenDialog(null);

To integrate this into a Swing app, you'll have to run it in the javafx thread via Platform.runLater (as seen here).

Please note that this will need you to initialize the javafx thread (in the example, this is done at the scene initialization, in new JFXPanel()).

To sum up, a ready to run solution in a swing app would look like this :

new JFXPanel(); // used for initializing javafx thread (ideally called once)
Platform.runLater(() -> {
    FileChooser fileChooser = new FileChooser();

    //Set extension filter
    FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
    FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
    fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);

    //Show open file dialog
    File file = fileChooser.showOpenDialog(null);
});

good question +1 , looks like as they "forgot" to implements something for Win7 (defaultLookAndFeel) into Java6, but for WinXP works correclty, and I hope too, that there must exists some Method/Properties for that

anyway you can try that with this code,

import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

class ChooserFilterTest {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                String[] properties = {"os.name", "java.version", "java.vm.version", "java.vendor"};
                for (String property : properties) {
                    System.out.println(property + ": " + System.getProperty(property));
                }
                JFileChooser jfc = new JFileChooser();
                jfc.showOpenDialog(null);
                jfc.addChoosableFileFilter(new FileFilter() {

                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".obj");
                    }

                    @Override
                    public String getDescription() {
                        return "Wavefront OBJ (*.obj)";
                    }

                    @Override
                    public String toString() {
                        return getDescription();
                    }
                });
                int result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
                System.out.println("Displayed description (Metal): " + (result == JOptionPane.YES_OPTION));
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    SwingUtilities.updateComponentTreeUI(jfc);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                jfc.showOpenDialog(null);
                result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
                System.out.println("Displayed description (System): " + (result == JOptionPane.YES_OPTION));
            }
        };
        SwingUtilities.invokeLater(r);
    }

    private ChooserFilterTest() {
    }
}

Couldn't make this work for directories though!! The DirectoryDialog throws us back to the tree style directory chooser which is the same as the one listed in the question. The problem is that it does not allow me to choose/select/open hidden folders. Nor does it allow for navigation to folders like AppData, ProgramData etc..

The Windows 7 style filedialog (swt) does allow navigation to these folders, but then again, does not allow for folder selection :(

Update To view hidden folders use JFileChooser and have setFileHidingEnabled(false). The only mandate with this is that users need to have 'show hidden files, folders and drives' selected in the

Folder Options -> View

of Windows Explorer

You won't get the flexibility of an address bar, but if you were looking around for a non-tree like file chooser in Java, which also lets you browse/view Hidden files/folder - then this should suffice

John McCarthy's answer seems to be the best. Here some suggestions.

import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.Image;

Add image on top left corner. It's important that you use "getResourceAsStream", you'll notice after export as Runnable jar:

Display display = new Display();
Shell shell = new Shell(display);
InputStream inputImage = getClass().getResourceAsStream("/app/launcher.png");
if (inputImage != null) {
    shell.setImage(new Image(display, inputImage));
}

User's home directory:

String filterPath = System.getProperty("user.home");

Get absolut pathname instead of filter-dependent pathname, which is wrong on other drive.

String absolutePath = dialog.open();

Since Swing emulates various L&F's, I guess your best bet would be to upgrade your JRE to the very latest and hope that the JFileChooser UI has been updated.

JFileChooser has always been a bit odd looking with Swing, also a bit slow.

Try using SWT's filechooser or you could wrap the C calls in JNA.

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