使用后台线程加载文件

This commit is contained in:
许轲 2023-08-10 15:26:28 +08:00
parent b387345d18
commit f424584caa

View File

@ -1,6 +1,7 @@
package org.jcnc.jnotepad; package org.jcnc.jnotepad;
import javafx.application.Application; import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.event.EventHandler; import javafx.event.EventHandler;
import javafx.geometry.Insets; import javafx.geometry.Insets;
@ -153,17 +154,30 @@ public class JNotepad extends Application {
FileChooser fileChooser = new FileChooser(); FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null); File file = fileChooser.showOpenDialog(null);
if (file != null) { if (file != null) {
try { Task<Void> openFileTask = new Task<>() {
getTXT(file); @Override
updateEncodingLabel(((TextArea) tabPane.getSelectionModel().getSelectedItem().getContent()).getText()); // 更新文本编码信息 protected Void call() throws Exception {
} catch (IOException e) { getTXT(file);
e.printStackTrace(); updateEncodingLabel(((TextArea) tabPane.getSelectionModel().getSelectedItem().getContent()).getText());
} return null;
} }
};
openFileTask.setOnSucceeded(e -> {
// 在任务完成后的操作更新界面等
});
openFileTask.setOnFailed(e -> {
// 在任务失败时的操作处理异常等
});
Thread thread = new Thread(openFileTask);
thread.start();
}
} }
} }
private void AutoSave(TextArea textArea) { private void AutoSave(TextArea textArea) {
// 在创建文本编辑区后添加文本变更监听器 // 在创建文本编辑区后添加文本变更监听器
textArea.textProperty().addListener((observable, oldValue, newValue) -> { textArea.textProperty().addListener((observable, oldValue, newValue) -> {