从控制台到GUI文本框/ lebel

时间:2017-01-14 19:24:00

标签: java javafx printing textbox console

我正在尝试为webdriver中的自动测试构建用户界面。

我的问题如何在标签或文本框中打印所有控制台行?

按钮上设置的方法:

    public void AutologinTest(ActionEvent event){
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("C:\\lottotest2\\workspace\\Lotteryscript\\Autologin.bat");
        BufferedReader input = new BufferedReader(
                new InputStreamReader(pr.getInputStream()));
        String line = null;
        while ((line = input.readLine()) != null)
            System.out.println(line);

    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:0)

您可以使用System.setOut(PrintStream流):

PrintStream ps = new PrintStream(
    new OutputStream() {
        public void write(int c){
            myLabel.setText(myLabel.getText() + (char) c);
        }
    }
);

System.setOut(ps);

System.out.println("Hello!"); // will print on the label

答案 1 :(得分:0)

您可以执行以下操作,将STDOUT重定向到TextArea或其他控件:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import java.io.PrintStream;

public class Main22 extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        TextArea textArea = new TextArea();

        primaryStage.setScene(new Scene(textArea));
        primaryStage.show();

        System.setOut(new PrintStream(System.out) {
            @Override
            public void write(byte[] buf, int off, int len) {
                super.write(buf, off, len);

                String msg = new String(buf, off, len);

                textArea.setText(textArea.getText() + msg);
            }
        });

        System.out.println("bla-bla-bla");
        System.out.println("Yet one line!");
    }
}

正如您所看到的,我只是覆盖了write的{​​{1}}方法,并为PrintStream中的文字附加了收到的短信。

screenshot of application

仅供参考:我不建议将TextArea用于显示日志,因为它在尝试处理大型文本时性能非常差。