JavaFX – 尝试使用BufferedReader时冻结 – 未闭合?
我已经尝试了几个小时试图解决这个问题,它已经开始惹恼我了。
我有一个简单的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 lsDevice = new EventHandler() { 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)
。
有帮助吗?
谢谢!
问题
问题是因为在JavaFX应用程序线程中处理长时间运行的任务而不是后台线程。
解
将处理工作移动到新任务中,然后单击按钮启动任务。
Task task = new Task () { @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()));
有关更多信息,请参阅JavaFX中的Concurrency 。
NB 即时编写代码。 可能包含错别字。