Does Swing support Windows 7-style file choosers?

前端 未结 10 2040
星月不相逢
星月不相逢 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:55

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

提交回复
热议问题