下面的类使用一个 JInternalFrame 来保存一个显示所有重定向的 println 和 err 语句的 Textarea。
public class ConsoleFrame extends JInternalFrame
{
JTextArea outArea = new JTextArea(10,100);
static JInternalFrame cons;
public ConsoleFrame()
{
outArea.setLineWrap(true);
JScrollPane pain = new JScrollPane(outArea);
//pain.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
this.add(pain);
this.setVisible(true);
this.setSize(1000,400);
this.setTitle("Groovy Console");
this.closable = false;
this.maximizable = false;
this.isSelected = true;
this.resizable = false;
BasicInternalFrameUI ui = (BasicInternalFrameUI)this.getUI();
Component north = ui.getNorthPane();
MouseMotionListener[] actions =
(MouseMotionListener[])north.getListeners(MouseMotionListener.class);
for (int i = 0; i < actions.length; i++)
north.removeMouseMotionListener( actions[i] );
this.setFocusable(false);
//logger
System.setErr(new PrintStream(new JTextAreaOutputStream(outArea)));
System.setOut(new PrintStream(new JTextAreaOutputStream(outArea)));
setConsole(this);
}
static public JInternalFrame getConsole(){
return cons;
}
public void setConsole(JInternalFrame console){
cons = console;
}
public class JTextAreaOutputStream extends OutputStream {
JTextArea ta;
public JTextAreaOutputStream(JTextArea t) {
super();
ta = t;
}
public void write(int i) {
ta.append(Character.toString((char)i));
}
public void write(char[] buf, int off, int len) {
String s = new String(buf, off, len);
ta.append(s);
}
}
}
此类仅重定向 sysout 和 syserr 语句。我应该在代码中进行哪些修改以将记录器语句重定向到文本区域?
最佳答案
您应该实现自定义 Log4J 记录器。有非常有用的基类可以扩展。我建议使用 org.apache.log4j.WriterAppender
。
关于java - 将 log4j 语句重定向到 java 中的自定义控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5645440/