JavaFX FileChooser Filefilter not returning extension

微笑、不失礼 提交于 2020-02-06 03:41:57

问题


In my project I use JavaFX FileChooser to let the user save files. I noticed a bug, where a file with a specified file filter would always save as a .txt on Linux systems. From another stackoverflow thread I leaned that unlike Windows, on Linux the fileChooser.showSaveDialog(); returns a file without the chosen file extension. I am confident, that this irregular implementation has a very obvious cause that I am not understanding. But still I am not sure how to adapt this for my needs.

I am aware that there are some other solved threads about a similar topic, but all the solutions are based on extracting the extension from the returned file, where in my case there is no extension returned by showSaveDialog.


回答1:


Here is an example that adds an extension if the user didn't type one using their selected filter:

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Save to file.");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            FileChooser fc = new FileChooser();
            FileChooser.ExtensionFilter xmlfilter = new FileChooser.ExtensionFilter("XML", "*.xml");
            FileChooser.ExtensionFilter mffilter = new FileChooser.ExtensionFilter("mf", "*.mf");
            fc.getExtensionFilters().addAll(xmlfilter,mffilter);
            fc.setSelectedExtensionFilter(xmlfilter);
            File f = fc.showSaveDialog(primaryStage.getOwner());
            System.out.println("f = " + f);
            if(null == f) {
                return;
            }
            final String selected_description = fc.getSelectedExtensionFilter().getDescription();
            System.out.println("selected_description = " + selected_description);          
            if(selected_description.equals(xmlfilter.getDescription()) && !f.getName().endsWith(".xml")) {
                f = new File(f.getParent(),f.getName()+".xml"); 
            } else if(selected_description.equals(mffilter.getDescription()) && !f.getName().endsWith(".mf")) {
                f = new File(f.getParent(),f.getName()+".mf");
            }
            System.out.println("f = " + f);
        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Example");
    primaryStage.setScene(scene);
    primaryStage.show();
}

I tested it on linux and never saw it add a .txt. A given extension filter might have multiple extensions so you will have to choose one to add arbitrarily.



来源:https://stackoverflow.com/questions/32757375/javafx-filechooser-filefilter-not-returning-extension

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