package htmlconsole;
import java.awt.BorderLayout;
public class HTMLConsole extends JFrame {
private JPanel contentPane;
private JTextPane textPane;
public class Interceptor extends PrintStream
{
public Interceptor(OutputStream out)
{
super(out,true);
}
@Override
public void print(String s)
{
super.print(s);
textPane.setText(textPane.getText()+s);
}
@Override
public void println(String s)
{
super.println(s);
textPane.setText(textPane.getText()+"\n<br>");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HTMLConsole frame = new HTMLConsole();
frame.setVisible(true);
System.out.println("Hello");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public HTMLConsole() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
textPane.setText("");
contentPane.add(textPane, BorderLayout.CENTER);
//redirect stream
PrintStream interceptor = new Interceptor(System.out);
System.setOut(interceptor);
}
}
Hellojava.lang.NullPointerException
at console.Console$Interceptor.print(Console.java:29)
at java.io.PrintStream.println(Unknown Source)
at console.Console$Interceptor.println(Console.java:35)
at console.Console$1.run(Console.java:47)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
我應該如何糾正這一計劃?這是非常令人困惑的是,這個異常被扔進尚未使用的「打印」方法中!
UPDATE:由textPane = new JTextPane();
更換JTextPane textPane = new JTextPane();
後
異常消失,但現在什麼都沒有顯示在窗口內。
這肯定叫,因爲你調用'System.setOut(攔截);'然後調用'System.out.println(「Hello」);',它自己調用'print()'。 –
請參閱['JTextComponent.read(Reader,Object)'](http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#read%28java.io。讀者%20java.lang.Object%29)。另外'setContentType(「text/html」);'沒有任何意義,因爲控制檯的輸出在任何意義上都不是* HTML。 –
@AndrewThompson好的,我已將我的課程更名爲「HTMLConsole」。 – 0x6B6F77616C74