我正在尝试更改我的UI的无限循环。但是直到循环结束我的UI才会改变。 我正在尝试使用Tasks,循环中的一个任务和另一个更改UI但我不知道如何传达任务。 在我的具体问题中,我正在做“ping 127.0.0.1”并且它返回一个无限的字符串。我可以在System.out中打印它,但在文本区域中不打印
工作的:
BufferedReader reader = SSH.execute(“ping 127.0.0.1”);
String linea;
String outputText = "";
while ((linea = reader.readLine()) != null)
{
outputText = outputText + linea +"\n" ;
System.out.println(linea);
}
//taTerminal.setText(outputText);
不起作用:
BufferedReader reader = SSH.execute(“ping 127.0.0.1”);
String linea;
String outputText = "";
while ((linea = reader.readLine()) != null)
{
outputText = outputText + linea +"\n" ;
taTerminal.setText(linea);
}
//taTerminal.setText(outputText);
答案 0 :(得分:2)
确保在后台任务中执行循环。您可以使用Task
的{{1}}来存储文本,因为它将在FX应用程序线程上正确更新。然后,您可以绑定观察消息属性并在更改时更新文本区域:
messageProperty
这适用于少量文本,但由于每次都要替换整个文本,因此效率非常低。更好的方法是使用@FXML private void actionStart(ActionEvent event1)throws Exception
{
final String cmd = tfCmd.getText();
final Task<Void> task = new Task<Void>()
{
@Override protected Void call() throws Exception
{
BufferedReader reader = SSH.execute(cmd);
String linea;
String outputText = "";
while ((linea = reader.readLine()) != null)
{
System.out.println(linea);
outputText = outputText + linea +"\n" ;
updateMessage(outputText);
}
return null;
}
};
task.messageProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> obs, String oldMessage, String newMessage) {
taTerminal.setText(task.getMessage());
}
});
Thread th = new Thread(task);
th.start();
}
将文本附加到文本区域:
Platform.runLater(...)
答案 1 :(得分:0)
我找到了解决方案,但并不是最好的解决方案。我用两个按钮:
@FXML private TextField tfCmd;
@FXML private TextArea taTerminal;
@FXML private Button btStart;
@FXML private Button btRefresh;
public Task<String> task;
public FXML_ExecuteInfiniteController()
{
this.task = new Task<String>()
{
@Override protected String call() throws Exception
{
String cmd = tfCmd.getText();
BufferedReader reader = SSH.execute(cmd);
String linea;
String outputText = "";
while ((linea = reader.readLine()) != null)
{
System.out.println(linea);
outputText = outputText + linea +"\n" ;
updateMessage(outputText);
}
return outputText;
}
};
}
@FXML private void actionStart(ActionEvent event1)throws Exception
{
Thread th = new Thread(task);
th.start();
}
@FXML private void actionRefresh(ActionEvent event1)throws Exception
{
taTerminal.setText(task.getMessage());
}