JavaFX FileChooser:如何设置文件过滤器?

2022-09-01 04:54:15

我想在JavaFX FileChooser中设置文件过滤器,但我找不到一种方法来做到这一点。

我的代码:

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

答案 1

你可以做:

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

下面是一个简单的示例:

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

JavaFX 和多扩展过滤器的更新:

FileChooser fc = new FileChooser();

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

fc.getExtensionFilters().add(fileExtensions);

推荐