Dev*_*rog 4 java multithreading javafx
实际上,我是Java线程的初学者。为了我的学习目的,我创建了一个简单的程序。我不知道我想念哪里。
码:
package javaguithread;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Controller {
Thread t1;
@FXML
TextField input;
@FXML
Label output;
@FXML
private void addData() {
output.setText(input.getText());
}
public void initialize() {
t1 = new Thread(() -> {
while (true) {
System.out.println(input.getText());
output.setText(input.getText());
}
});
t1.start();
}
}
Run Code Online (Sandbox Code Playgroud)
它显示的错误是
at com.sun.javafx.tk.Toolkit.checkFxUserThread(
Toolkit.java:236)
Run Code Online (Sandbox Code Playgroud)
更新
我尝试用我创建的另一个类初始化线程。她的是我的代码。
package javathreadgui;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Controller {
private class GuiUpdater extends Task<Void> {
Controller ctrl;
GuiUpdater(Controller ctrl) {
this.ctrl = ctrl;
}
@Override
protected Void call() throws Exception {
makeChanges();
return null;
}
private void makeChanges(){
while(true){
Platform.runLater(() -> {
ctrl.output.setText(ctrl.input.getText());
});
System.out.println("test");
}
}
}
@FXML
TextField input;
@FXML
Label output;
public void initialize() {
System.out.println("Hello ");
Task<Void> task = new GuiUpdater(this);
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
}
Run Code Online (Sandbox Code Playgroud)
当我将控制台输出作为时,它很好地工作
System.out.println("test");
Run Code Online (Sandbox Code Playgroud)
否则GUI冻结。我该怎么办?
UI的任何更改都必须在JavaFX Thread上进行。用以下代码包装setText()调用:
Platform.runLater(new Runnable() {
@Override public void run() {
output.setText(input.getText());
}
});
Run Code Online (Sandbox Code Playgroud)
您可以搜索大量关于并发以及如何通过任务/线程更新UI的帖子。但是,如果您真的不想深入研究细节,则只需知道每个UI更新都必须在Platform.runLater(...)调用中即可。
编辑:
这是一个可能对您有所帮助的示例:
import java.util.Scanner;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class LabelUpdateTest extends Application {
private Label label;
@Override
public void start(Stage stage) throws Exception {
label = new Label("Waiting for input..");
stage.setScene(new Scene(label, 100, 100));
stage.show();
initInputThread();
}
private void initInputThread() {
Scanner input = new Scanner(System.in);
Task<Void> task = new Task<Void>() {
@Override
protected Void call() {
while (true) {
String userInput = input.nextLine();
Platform.runLater(new Runnable() {
@Override
public void run() {
label.setText("Input was : " + userInput);
}
});
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2051 次 |
| 最近记录: |