在JavaFX中使用大型txt文件(TextArea替代?)

时间:2017-06-28 07:47:24

标签: java javafx

我创建了一个简单的GUI,我有一个TextAreaTextArea本身将由Array填充,其中包含.txt文件中的扫描字符串。

这适用于较小尺寸的文件。但是,当使用大文件(每个文本文件大约5MB)时,TextArea(只有TextArea)感觉迟钝和缓慢(不像我想的那样响应)。是否有TextArea的替代方案(不必在JavaFX中)?

我正在寻找一些非常简单的东西,这基本上可以让我得到&设置文本。与Slidercontrol JavaFX一样,TextArea会非常方便。

谢谢你,祝你有个美好的一天!

编辑:我的代码的一个非常基本的例子:

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

2 个答案:

答案 0 :(得分:5)

基于@Matt的answer和@ SedrickJefferson的suggestion,这是一个完整的例子。

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

答案 1 :(得分:2)

感谢@SedrickJefferson,我将TextArea替换为ListView。它现在运行得非常顺畅。除此之外,由于性能问题,我将Scanner替换为BufferedReader

相关问题