怎樣把控制台中輸出的東西在Frame框架中的滾動窗口中輸出。在線急等賜教
// 核心代碼就是重定向輸出流的位置,這裡需要復寫print方法
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class OutCapture extends JFrame {
private static final long serialVersionUID = -7094759145284455963L;
public OutCapture() {
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
final JTextArea textArea = new JTextArea();
JScrollPane scrollPanel = new JScrollPane();
scrollPanel.setViewportView(textArea);
contentPane.add(scrollPanel, BorderLayout.CENTER);
JButton btn = new JButton("輸出");
contentPane.add(btn, BorderLayout.SOUTH);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
});
// 核心代碼就是重定向輸出流的位置,這裡需要復寫print方法
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
}
}, true) {
@Override
public void print(String txt) {
textArea.append(txt);
textArea.setCaretPosition(textArea.getText().length());
}
@Override
public void println(String txt) {
print(txt + "\n");
}
@Override
public void print(boolean b) {
print(b ? "true" : "false");
}
public void println(boolean b) {
print(String.valueOf(b) + "\n");
}
@Override
public void print(char c) {
print(String.valueOf(c));
}
public void println(char c) {
print(String.valueOf(c) + "\n");
}
@Override
public void print(int i) {
print(String.valueOf(i));
}
public void println(int i) {
print(String.valueOf(i) + "\n");
}
@Override
public void print(long l) {
print(String.valueOf(l));
}
public void println(long l) {
print(String.valueOf(l) + "\n");
}
@Override
public void print(double d) {
print(String.valueOf(d));
}
public void println(double d) {
print(String.valueOf(d) + "\n");
}
@Override
public void print(float f) {
print(String.valueOf(f));
}
public void println(float f) {
print(String.valueOf(f) + "\n");
}
@Override
public void print(char s[]) {
print(String.valueOf(s));
}
public void println(char s[]) {
print(String.valueOf(s) + "\n");
}
@Override
public void print(Object obj) {
print(String.valueOf(obj));
}
public void println(Object obj) {
print(String.valueOf(obj) + "\n");
}
});
}
public static void main(String[] args) {
OutCapture oc = new OutCapture();
oc.setLocationRelativeTo(null);
oc.setSize(400, 400);
oc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
oc.setVisible(true);
}
}