我已经尝试了几个小时试图解决这个问题,但它已经开始惹恼我了。
我有一个简单的JavaFX应用程序,然后当单击一个按钮时,它
执行Process p = pb.start()
该命令运行,可以在终端窗口中看到,但GUI完全冻结。
//A lot of unused imports I know...
public class GUI extends Application {
GridPane grid;
Scene scene;
Button btn1;
Button btn2;
TextArea text;
Label lbl1;
Label lbl2;
@Override
public void start(Stage primaryStage) throws IOException {
primaryStage.setTitle("Flashing - ROMMING - Recovery - Rooting");
grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setGridLinesVisible(true);
scene = new Scene(grid,1000, 1000);
text = new TextArea();
text.setText("Commands will be Shown Here");
btn1 = new Button("ADB List Devices");
btn2 = new Button("ADB Reboot");
btn1.setMinSize(50, 25);
btn2.setMinSize(50, 25);
btn1.addEventHandler(ActionEvent.ACTION, lsDevice);
grid.add(btn1, 0, 1);
grid.add(btn2, 0, 2);
grid.add(text, 0, 3);
primaryStage.setScene(scene);
primaryStage.show();
}
//Logger
//Event Handlers
EventHandler<ActionEvent> lsDevice = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
System.out.println("Handling event " + e.getEventType());
ProcessBuilder pb = new ProcessBuilder().command("cmd.exe");
File log = new File("log");
String line = null;
try {
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
// read the output from the command
while((line=stdInput.readLine())!=null){
System.out.println(line);
}
}
catch (Exception e1) {
e1.printStackTrace();
}
e.consume();
}
};
}
任何帮助都将不胜感激。
在旁注中,我的场景中有一个TextArea
,我想在命令运行时更新。
例如,如果点击ver
按钮,则TextArea
我希望它更新。我试过text.appendText(string)
。
任何帮助?
谢谢!
答案 0 :(得分:2)
问题是因为在JavaFX应用程序线程中处理长时间运行的任务而不是后台线程。
将处理工作移至新任务中,并在单击按钮时启动任务。
Task<String> task = new Task<String>() {
@Override
protected Integer call() throws Exception {
try {
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
// read the output from the command
while((line=stdInput.readLine())!=null){
System.out.println(line);
// To update the textarea
updateMessage(line);
}
}
catch (Exception e1) {
e1.printStackTrace();
}
}
};
处理程序内部:
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
textarea,您可以将其绑定为
textarea.textProperty().bind().(Bindings.concat(textArea.getText()).concat(task.messageProperty()));
有关详情,请浏览Concurrency in JavaFX。
N.B。 即时编写代码。可能包含拼写错误。