Does Swing support Windows 7-style file choosers?

前端 未结 10 2050
星月不相逢
星月不相逢 2020-11-28 08:26

I just added a standard \"Open file\" dialog to a small desktop app I\'m writing, based on the JFileChooser entry of the Swing Tutorial. It\'s generating a

10条回答
  •  忘掉有多难
    2020-11-28 08:54

    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 ();
        }
    } 
    

提交回复
热议问题