如何在JavaFX中实时更新textarea(控制台),而不会丢失流或冻结应用程序 [英] How to update textarea(console)in realtime in JavaFX without loosing flow or freezing the application

查看:6332
本文介绍了如何在JavaFX中实时更新textarea(控制台),而不会丢失流或冻结应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的JFX,我正在努力这个。我试图运行一个简单的模拟,必须打印输出(system.out和system.err)到textarea。

I am new JFX and I am struggling with this. I am trying to run a simple simulation that has to print output (system.out and system.err) to textarea.

 public class ConsoleController {
    @FXML
    public TextArea consoleLogscreen;

    private class Console extends OutputStream {

        @Override
        public void write(int b) throws IOException {
            consoleLogscreen.appendText(String.valueOf((char) b));
        }
    }

    @FXML
    public void initialize() throws IOException {
        Console console = new Console();
        PrintStream ps = new PrintStream(console, true);
        System.setOut(ps);
        System.setErr(ps);
        System.err.flush();
        System.out.flush();
    }
}

SimulationController:

SimulationController:

 public class SimulationController {
    @FXML
    private Button homebutton;
    @FXML
    private Button abortbutton;
    private volatile Service<Void> backgroundThread;
    private volatile Thread t;
    private volatile Simulate sim;
    @FXML
    public void initialize() {
        sim = new Simulate();
        t = new Thread(sim);
        backgroundThread = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        t.run();
                        return null;
                    }
                };
            }
        };
        backgroundThread.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {
                t.interrupt();
                sim.shutDown(true);
            }
        });
        backgroundThread.restart();
        abortbutton.setDisable(false);
        homebutton.setDisable(true);
    }
    @FXML
    void onAbortClicked(ActionEvent event) throws IOException {
        if (event.getSource() == abortbutton) {
            backgroundThread.cancel();
        }
    }
    @FXML
    void onHomeClicked(ActionEvent event) throws IOException {
        if (event.getSource() == homebutton) {
            Utility.getHome((Stage) homebutton.getScene().getWindow());
        }
    }
}

Simulation.fxml: p>

Simulation.fxml:

<Pane prefHeight="500.0" prefWidth="750.0"xmlns="http://javafx.com/javafx/8"      xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.jfxabstract.view.SimulationController">
   <children>
      <Button fx:id="abortbutton" alignment="CENTER" contentDisplay="CENTER" layoutX="250.0" layoutY="430.0" mnemonicParsing="false" onAction="#onAbortClicked" styleClass="custombutton" text="Abort" textAlignment="CENTER" />
      <Button fx:id="homebutton" alignment="CENTER" contentDisplay="CENTER" layoutX="450.0" layoutY="430.0" mnemonicParsing="false" onAction="#onHomeClicked" styleClass="custombutton" text="Home" textAlignment="CENTER" />
      <fx:include source="Console.fxml" />
   </children>
</Pane>

我使用javafx.concurrent.service来运行我的任务,但应用程序冻结,输出不是实时的。

I am using javafx.concurrent.service to run my task but the application is freezing and also the printing the output is not in realtime.

任何人都可以建议我可能出错的地方。

Can anyone suggest where I might have gone wrong.

更新:

运行方法从数据库中检索数据,通过调用相同类中的其他方法进行验证。对于简单的抽象应用程序我使用这个

the run method retrieves data from database and runs few validations by invoking other methods in same class. For simple abstract application I am using this

public void run() {
    long i = 1;
    while (i < 90) {
        double k = Math.sqrt(Math.pow(i, 2) / Math.sqrt(i));
        System.out.println("i: " + i + " Count: " + k);
        if (!shutdown) {
            break;
        }
        i++;
    }
}


推荐答案

这个例子我做了一个代码来获取System.out.println并实时更新

With this example i made a code to get System.out.println and to update on real time

/**
 * 
 * @param str
 */
public void appendText(String str) {

    results.append(str);

    updated = true;
}

/**
 * 
 */
public void setupConsoleOutput() {

    backgroundThread = new Service<String>() {

        protected Task<String> createTask() {

            return new Task<String>() {

                protected String call() throws Exception {

                    while (true) {

                        if (isCancelled()) {

                            break;
                        }

                        if (updated) {

                            updateValue(results.toString());

                            updated = false;

                            Platform.runLater(() -> {

                                consoleOutput.setScrollTop(Double.MAX_VALUE);
                            });
                        }

                        if (exported) {

                            consoleOutput.setScrollTop(Double.MAX_VALUE);

                            exported = false;
                        }

                        Thread.sleep(100);
                    }

                    return results.toString();
                }
            };
        }
    };

    consoleOutput.textProperty().bind(backgroundThread.valueProperty());

    backgroundThread.start();

    backgroundThread.setOnCancelled(new EventHandler<WorkerStateEvent>() {

        public void handle(WorkerStateEvent event) {

        }
    });

    backgroundThread.restart();

    OutputStream out = new OutputStream() {

        @Override
        public void write(int b) throws IOException {

            appendText(String.valueOf((char) b));
        }
    };

    PrintStream ps = new PrintStream(out, true);

    System.setOut(ps);

    System.setErr(ps);
}

并为我工作。

这篇关于如何在JavaFX中实时更新textarea(控制台),而不会丢失流或冻结应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆