JavaFX FileChooser: how to set file filters?

前端 未结 3 1405
梦如初夏
梦如初夏 2021-02-05 01:18

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(\"M         


        
3条回答
  •  心在旅途
    2021-02-05 01:41

    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() {
    
                @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();
        }
    }
    

提交回复
热议问题