實現輸出從控制台到GUI並不復雜
重定向標准輸出很easy
// GUIPrintStream guiPrintStream = new GUIPrintStream(System
System
System
在上面的代碼中
Java代碼
/**//*
* To change this template
* and open the template in the editor
*/
import java
import java
import javax
import javax
/** *//**
* 輸出到文本組件的流
*
* @author Chen Wei
* @website www
* @email chenw
*/
public class GUIPrintStream extends PrintStream
private JTextComponent component;
private StringBuffer sb = new StringBuffer();
public GUIPrintStream(OutputStream out
super(out);
ponent = component;
}
/** *//**
* 重寫write()方法
* @param buf
* @param off
* @param len
*/
@Override
public void write(byte[] buf
final String message = new String(buf
SwingUtilities
public void run()
sb
component
}
});
}
}
/**//*
* To change this template
* and open the template in the editor
*/
import java
import java
import javax
import javax
/** *//**
* 輸出到文本組件的流
*
* @author Chen Wei
* @website www
* @email chenw
*/
public class GUIPrintStream extends PrintStream
private JTextComponent component;
private StringBuffer sb = new StringBuffer();
public GUIPrintStream(OutputStream out
super(out);
ponent = component;
}
/** *//**
* 重寫write()方法
* @param buf
* @param off
* @param len
*/
@Override
public void write(byte[] buf
final String message = new String(buf
SwingUtilities
public void run()
sb
component
}
});
}
}
類 GUIPrintStream
GUIPrintStream 在構造函數中增加了一個 JTextComponent 變量
簡單的代碼完成了將標准輸出重定向到 GUI 的全過程
測試
Java代碼
public class MainFrame extends javax
public MainFrame() {
initComponents();
// 重定向到通過文本組件構建的組件輸出流中
System
}
private void initComponents() {
scrollPane = new javax
textArea = new javax
btnOut = new javax
setDefaultCloseOperation(javax
setTitle(
textArea
textArea
scrollPane
getContentPane()
btnOut
btnOut
public void actionPerformed(java
btnOutActionPerformed(evt);
}
});
getContentPane()
pack();
}
private void btnOutActionPerformed(java
System
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java
public void run() {
new MainFrame()
}
});
}
private javax
private javax
private javax
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25870.html