我想要的只是在程序运行时更新标签。我正在读取一些文件,我希望它显示正在读取的文件的名称。
但是,它仅使用以下代码显示最后一个文件(基本上 GUI 在整个过程完成之前不会响应):
static Text m_status_update = new Text(); //I declared this outside the function so dont worry
m_status_update.setText("Currently reading " + file.getName());
我有大约 4-5 个文件,我只想显示名称。
我看到一个类似的问题在 JavaFx 标签中显示变化的值,最佳答案推荐如下:
Label myLabel = new Label("Start"); //I declared this outside the function so dont worry
myLabel.textProperty().bind(valueProperty);
但是 valueProperty 是一个 StringProperty,我一直无法将字符串转换为字符串属性。
另外,我还看到了这个刷新JAVAFX中的标签,但 OP 会根据操作更新标签。我真的没有任何行动吗?
如果您在 FX 应用程序线程上运行整个进程,则该线程(实际上)与用于显示 UI 的线程相同。如果 UI 的显示和文件迭代过程都在同一线程中运行,则一次只能发生一个。因此,您可以在该过程完成之前阻止 UI 更新。
这是一个简单的示例,我在每次迭代之间暂停 250 毫秒(模拟读取相当大的文件)。通过一个按钮即可在 FX 应用程序线程中启动此程序(请注意,此程序运行时 UI 如何无响应 - 您无法在文本字段中键入内容)。另一个按钮使用Task
要在后台运行它,请在 FX 应用程序线程上正确安排对 UI 的更新。
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class UpdateTaskDemo extends Application {
@Override
public void start(Stage primaryStage) {
Label label = new Label();
Button runOnFXThreadButton = new Button("Update on FX Thread");
Button runInTaskButton = new Button("Update in background Task");
HBox buttons = new HBox(10, runOnFXThreadButton, runInTaskButton);
buttons.setPadding(new Insets(10));
VBox root = new VBox(10, label, buttons, new TextField());
root.setPadding(new Insets(10));
runOnFXThreadButton.setOnAction(event -> {
for (int i=1; i<=10; i++) {
label.setText("Count: "+i);
try {
Thread.sleep(250);
} catch (InterruptedException exc) {
throw new Error("Unexpected interruption");
}
}
});
runInTaskButton.setOnAction(event -> {
Task<Void> task = new Task<Void>() {
@Override
public Void call() throws Exception {
for (int i=1; i<=10; i++) {
updateMessage("Count: "+i);
Thread.sleep(250);
}
return null ;
}
};
task.messageProperty().addListener((obs, oldMessage, newMessage) -> label.setText(newMessage));
new Thread(task).start();
});
primaryStage.setScene(new Scene(root, 400, 225));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)