Using large txt files in JavaFX (alternatives to TextArea?)

I created a simple GUI where I have TextArea . TextArea itself will be populated with an Array that contains the scanned lines from the .txt file.

This is great for smaller files. However, when using large files (~ 5 MB per txt. File), TextArea (and only TextArea ) feels slow and slow (not as responsive as we would like). Is there an alternative to TextArea (shouldn't be in JavaFX )?

I am looking for something very simple, which basically allows me to get and set the text. Slidercontrol , as in JavaFX TextArea , would be very convenient.

Thank you, have a great day!

Edit: a very simple example of my code:

 public class Main extends Application { public void start(Stage stage) { Pane pane = new Pane(); TextField filePath = new TextField("Filepath goes in here..."); TextArea file = new TextArea("Imported file strings go here..."); file.relocate(0, 60); Button btnImport = new Button("Import file"); btnImport.relocate(0, 30); ArrayList<String> data = new ArrayList<>(); btnImport.setOnAction(e -> { File fileToImport = new File(filePath.getText()); try { Scanner scanner = new Scanner(fileToImport); while(scanner.hasNextLine()) { data.add(scanner.nextLine()); } file.setText(data.toString()); } catch (FileNotFoundException e1) { e1.printStackTrace(); } }); pane.getChildren().addAll(filePath, file, btnImport); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } public static void main(String[] args){ launch(); } } 
+5
source share
2 answers

Based on @Matt answer and @SedrickJefferson, here is a complete example.

image

 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(); } } 
+5
source

Thanks @SedrickJefferson, I replaced TextArea with ListView . Now it works very smoothly. In addition, I replaced Scanner with BufferedReader due to performance.

+2
source

Source: https://habr.com/ru/post/1269281/


All Articles