在JavaFX中,可以通过以下步骤将输出从System.out重定向到JavaFX的TextArea组件:
TextArea textArea = new TextArea();
PrintStream printStream = new PrintStream(new TextAreaOutputStream(textArea));
System.setOut(printStream);
import java.io.IOException;
import java.io.OutputStream;
public class TextAreaOutputStream extends OutputStream {
private TextArea textArea;
public TextAreaOutputStream(TextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
textArea.appendText(String.valueOf((char) b));
}
}
以下是一个完整的示例代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class RedirectSystemOut extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
PrintStream printStream = new PrintStream(new TextAreaOutputStream(textArea));
System.setOut(printStream);
System.out.println("Hello, World!");
StackPane root = new StackPane(textArea);
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.show();
}
public static class TextAreaOutputStream extends OutputStream {
private TextArea textArea;
public TextAreaOutputStream(TextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
textArea.appendText(String.valueOf((char) b));
}
}
}
这样,输出的内容将显示在JavaFX的TextArea组件中。你可以根据需要将此代码集成到你的JavaFX应用程序中,并根据实际情况进行调整和扩展。
领取专属 10元无门槛券
手把手带您无忧上云