我有一个简单的JavaFX 2应用程序,有2个按钮,分别是Start和Stop.单击开始按钮时,我想创建一个后台线程,它将进行一些处理并在其进行时更新UI(例如进度条).如果单击停止按钮,我希望线程终止.
我尝试使用javafx.concurrent.Task我从文档中收集的类可以正常工作.但是每当我单击"开始"时,UI都会冻结/挂起而不是保持正常.
她是主Myprogram extends Application类中用于显示按钮的代码:
public void start(Stage primaryStage)
{
final Button btn = new Button();
btn.setText("Begin");
//This is the thread, extending javafx.concurrent.Task :
final MyProcessor handler = new MyProcessor();
btn.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent event)
{
handler.run();
}
});
Button stop = new Button();
stop.setText("Stop");
stop.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent event)
{
handler.cancel();
}
}
);
// Code for adding the UI controls to the stage here.
}
Run Code Online (Sandbox Code Playgroud)
这是MyProcessor类的代码:
import …Run Code Online (Sandbox Code Playgroud) 我有一个简单的自定义日志框架,如下所示:
package something;
import javafx.scene.control.TextArea;
public class MyLogger {
public final TextArea textArea;
private boolean verboseMode = false;
private boolean debugMode = false;
public MyLogger(final TextArea textArea) {
this.textArea = textArea;
}
public MyLogger setVerboseMode(boolean value) {
verboseMode = value;
return this;
}
public MyLogger setDebugMode(boolean value) {
debugMode = value;
return this;
}
public boolean writeMessage(String msg) {
textArea.appendText(msg);
return true;
}
public boolean logMessage(String msg) {
return writeMessage(msg + "\n");
}
public boolean logWarning(String msg) {
return writeMessage("Warning: …Run Code Online (Sandbox Code Playgroud) 我正在使用Java FX textarea,并将其用作后续步骤的信息。
步骤如下。复制文件。删除旧文件。复制新文件。然后将一些属性从旧文件复制到新文件。
单击按钮将开始整个步骤。
我面临的问题是,一旦使用append命令,文本区域就不会被更新。
append命令添加数据,并且当函数终止时,我将所有文本放在一起。我希望在调用函数时更新文本区域。
在我的程序中,复制文件操作需要一些时间,因为它是一个大文件。因此,在开始时,我显示操作已开始的消息。在操作结束时,我要显示的操作已结束。
但是文本区域将所有这些文本一起显示。
我在oracle论坛中读到,FX中的文本区域使用单个线程,因此在整个过程完成之前不会显示任何内容。
文章:https : //community.oracle.com/message/9938117#9938117
谁能建议我该怎么办?
新编辑
单击按钮上的“确定”。我正在调用一个函数,该函数执行以下方法。
public void executeCmds(){
createTempDirectory();
copyConfigPropetiesFileValues();
copyConfigProperties();
copyYMLFile();
copyYMLFileProperties();
stopTomcatServer();
deleteOldWar();
copyNewWar();
startTomcatServer();
copyOldConfigFile();
copyOldYMLFile();
}
Run Code Online (Sandbox Code Playgroud)
现在,每个功能都是一个过程,应按顺序执行。并且在完成每个步骤之后,我想用成功消息更新GUI文本区域来完成此操作。
对于我正在使用的方法如下:
public void createTempDirectory(){
//Creating temporary directory for copying property files
status_text_area.appendText("Trying to create a temp directory \n");
File tempDir= new File(tomcat_path.getText()+filePath.path_to_temp_directory);
if(!tempDir.exists())
tempDir.mkdirs();
status_text_area.appendText("Created Temp directory to copy Config Files \n");
}
Run Code Online (Sandbox Code Playgroud)
与其他功能相同。copyWar文件功能和delete warfile功能需要一段时间,因为它将130 MB文件从一个位置复制到另一个位置。
所以我希望将textarea显示为:1.开始复制文件,并在一段时间后
但是问题是,在执行所有功能之前,文本区域根本不会填充。
如果我尝试通过线程执行这些命令,那么执行顺序就不予保证。请帮忙