Using large txt files in JavaFX(TextArea alternatives?)

前端 未结 2 939
陌清茗
陌清茗 2020-12-19 11:50

I created a simple GUI where I have a TextArea. The TextArea itself will be populated by an Array, which contains scanned Strings out

相关标签:
2条回答
  • 2020-12-19 12:13

    Based on @Matt's answer and @SedrickJefferson's suggestion, here's a complete example.

    import java.io.*;
    import javafx.application.*;
    import javafx.collections.*;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage stage) {
            VBox pane = new VBox();
            Button importButton = new Button("Import");
            TextField filePath = new TextField("/usr/share/dict/words");
            ObservableList<String> lines = FXCollections.observableArrayList();
            ListView<String> listView = new ListView<>(lines);
            importButton.setOnAction(a -> {
                listView.getItems().clear();
                try {
                    BufferedReader in = new BufferedReader
                        (new FileReader(filePath.getText())); 
                    String s;
                    while ((s = in.readLine()) != null) {
                        listView.getItems().add(s);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            pane.getChildren().addAll(importButton, filePath, listView);
            Scene scene = new Scene(pane);
            stage.setScene(scene);
            stage.show();
        }
    }
    
    0 讨论(0)
  • 2020-12-19 12:16

    Thanks to @SedrickJefferson I replaced the TextArea with a ListView. It runs very smooth now. Besides that I will replace the Scanner with a BufferedReader, due to performance issues.

    0 讨论(0)
提交回复
热议问题