Search code examples
javafxfilechooser

How to open Photos by the FileChooser with a certain extension with JavaFX?


I'm making photo manager and I'm searching to know how to get files from the FileChooser with some extension:*.png - *.jpg ... So which method should I use or which code should I do ?

I tried this: fileChooser.getExtensionFilters(); but it does not anything.

Can any body help me?


Solution

  • The FileChooser class has a nested class ExtensionFilter. First you have to create an Instance of it:

    FileChooser.ExtensionFilter imageFilter
        = new FileChooser.ExtensionFilter("Image Files", "*.jpg", "*.png");
    

    afterwards you can add this Instance to your FileChooser's Extension list:

    FileChooser fc = new FileChooser();
    fc.getExtensionFilters().add(imageFilter);
    

    A Minimal Complete Verifiable Example code is down below:

    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.FileChooser;
    import javafx.stage.Stage;
    
    public class FileChooserTest extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        FileChooser.ExtensionFilter imageFilter
            = new FileChooser.ExtensionFilter("Image Files", "*.jpg", "*.png");
    
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().add(imageFilter);
    
        Button btn = new Button();
        btn.setText("Open File");
        btn.setOnAction((ActionEvent event) -> {
          fc.showOpenDialog(primaryStage);
        });
    
        StackPane root = new StackPane();
        root.getChildren().add(btn);
    
        Scene scene = new Scene(root, 300, 250);
    
        primaryStage.setTitle("FileChooser Demo");
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    }