Haeri
Haeri

Reputation: 701

JavaFX FileChooser Filefilter not returning extension

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.

Upvotes: 1

Views: 1218

Answers (1)

WillShackleford
WillShackleford

Reputation: 7018

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.

Upvotes: 4

Related Questions