我希望在我的java程序中创建一个单独的窗口,以基本上显示我使用println()打印的内容。如果以"错误:"开头,有一些方法可以使某些文本读取和/或加粗。这样做有简单或直接的方法吗?
答案 0 :(得分:0)
一种简单的方法是编写一个以String
作为参数的函数,然后1)使用System.out.print*()
打印到控制台,然后打印或复制文本到该窗口' s JTextField
,或构造函数,或用于在该窗口中打印文本的任何方法,即:
public method printAndCopyText(String text) {
System.out.println(text);
otherWindowObject.getTextFieldObject().setText(text);
}
答案 1 :(得分:0)
这是一个示例
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
public class JConsole {
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("JConsole");
JTextPane jta = new JTextPane();
JButton button = new JButton("Run");
frame.setLayout(new BorderLayout());
frame.add(button,BorderLayout.NORTH);
frame.add(jta,BorderLayout.CENTER);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Object>(){
@Override
protected Void doInBackground() throws Exception {
outputTest("inner");
return null;
}}.execute();
}});
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
console(jta);
}
public static void outputTest(String msg){
for(int i=0;i<10;i++){
System.out.println(i+" "+msg);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public static void console(final JTextPane area) throws IOException {
area.setContentType("text/html");
final PipedInputStream outPipe = new PipedInputStream();
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()){
String line = s.nextLine();
publish(line + "\n");
}
return null;
}
@Override
protected void process(List<String> chunks) {
for (String line : chunks){
area.setText("<font size=\"3\" color=\"red\">"+line+"</font>");
}
}
}.execute();
}
}