Java 从控制台到GUI文本框/lebel的打印行
我正在尝试为webdriver中的自动测试构建用户界面 我的问题是如何打印标签或文本框中的所有控制台行 在按钮上设置的方法:Java 从控制台到GUI文本框/lebel的打印行,java,javafx,printing,textbox,console,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.ba
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();
}
您可以使用System.setOut(打印流):
您可以执行类似操作,将
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!");
}
}
如您所见,我只是覆盖了PrintStream
的write
方法,并为TextArea
中的文本追加传入的文本消息
仅供参考:我不建议将
TextArea
用于显示日志,因为它在处理大文本时性能非常差。请将您的问题包括在代码中,而不是发布代码的屏幕截图。您不清楚要做什么。如果您正在创建用户界面,它应该使用控制台进行I/O,或者使用GUI进行I/O,但不能同时使用两者。如果您不希望它出现在控制台中,请不要使用System.out.println
(它会向控制台发送一些信息)。只需将文本附加到所引用的任何控件。TextArea
可能是最自然的用法而不是System.out.println
但是在lebel中它只显示一行为什么不执行lebel.setText(lebel.getText()+“\n”+行)代码>??或者,如果是TextArea
,只需执行lebel.appendText(“\n”+行)代码>?这是一种非常迂回的向控件追加文本的方法。为什么要使用System.out.println(…)
????
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!");
}
}