我一直在从事一个项目,就功能而言,它可以完全正常工作,但我只是将其打印到控制台中。我想用JFrame在新窗口中打印它,这样我就可以用它制作一个jar文件,并且不需要使用ide就可以运行它。如何在现有代码中添加JFrame或其他工具,使其在新窗口中打印文本?
答案 0 :(得分:0)
已在How to set output stream to TextArea
中实现上述实现的“非常基础”示例。
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Test extends Application {
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
PrintStream ps = System.out;
System.setOut(new PrintStream(new StreamCapturer("STDOUT", new Consumer() {
@Override
public void appendText(String text) {
Platform.runLater(new Runnable() {
@Override
public void run() {
textArea.appendText(text);
}
});
}
}, ps)));
BorderPane root = new BorderPane(textArea);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Just going to output the current time");
try {
while (true) {
Thread.sleep(1000);
System.out.println(new Date());
}
} catch (InterruptedException ex) {
}
}
});
t.setDaemon(true);
t.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public interface Consumer {
public void appendText(String text);
}
public class StreamCapturer extends OutputStream {
private StringBuilder buffer;
private String prefix;
private Consumer consumer;
private PrintStream old;
public StreamCapturer(String prefix, Consumer consumer, PrintStream old) {
this.prefix = prefix;
buffer = new StringBuilder(128);
buffer.append("[").append(prefix).append("] ");
this.old = old;
this.consumer = consumer;
}
@Override
public void write(int b) throws IOException {
char c = (char) b;
String value = Character.toString(c);
buffer.append(value);
if (value.equals("\n")) {
consumer.appendText(buffer.toString());
buffer.delete(0, buffer.length());
buffer.append("[").append(prefix).append("] ");
}
old.print(c);
}
}
}