JavaFX FileChooser: how to set file filters?

℡╲_俬逩灬. 提交于 2019-12-09 04:28:09

问题


I want to set file filters in a JavaFX FileChooser but I could not find a way to do it.

My code:

  FileChooser fc = new FileChooser();
  fc.setTitle("My File Chooser");
  File f = fc.showOpenDialog(primaryStage);
  System.out.println(f);

回答1:


You could do:

FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
chooser.getExtensionFilters().add(extFilter);

Here is a simple example:

public class ExtensionFilterExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Extension Filter Example");

        final Label fileLabel = new Label();

        Button btn = new Button("Open FileChooser");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                FileChooser fileChooser = new FileChooser();

                // Set extension filter
                FileChooser.ExtensionFilter extFilter = 
                        new FileChooser.ExtensionFilter("TEXT files (*.txt)", "*.txt");
                fileChooser.getExtensionFilters().add(extFilter);

                // Show open file dialog
                File file = fileChooser.showOpenDialog(primaryStage);
                if (file != null) {
                    fileLabel.setText(file.getPath());
                }
            }
        });

        VBox vBox = new VBox(30);
        vBox.getChildren().addAll(fileLabel, btn);
        vBox.setAlignment(Pos.BASELINE_CENTER);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}



回答2:


Update for JavaFX plus multiple extensions filter:

FileChooser fc = new FileChooser();

FileChooser.ExtensionFilter fileExtensions = 
  new FileChooser.ExtensionFilter(
    "Web pages", "*.tpl", "*.html", "*.htm");

fc.getExtensionFilters().add(fileExtensions);



回答3:


This is How you can do it.

FileChooser fc=new FileChooser();
FileChooser.ExtensionFilter fileExtensions =new FileChooser.ExtensionFilter("music files","*.mp3", "*.mp4");
fc.getExtensionFilters().add(fileExtensions);
List<File> selectedFiles=fc.showOpenMultipleDialog(null);       
if(selectedFiles!=null){
     for(int i=0;i<selectedFiles.size();i++){
           System.out.println(selectedFiles.get(i).toString());
     }
}


来源:https://stackoverflow.com/questions/13634576/javafx-filechooser-how-to-set-file-filters

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