Redirecting System.out to JTextPane

后端 未结 3 1894
小鲜肉
小鲜肉 2020-11-28 14:39

I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err t

3条回答
  •  野性不改
    2020-11-28 15:24

    In the following link you can find the MessageConsole class that someone mentioned. I implemented a software and used this solution and it works perfect for me. I used the Netbeans design tool, so the code regarding the visual appearance of the JTextPane is a bit cumbersome, so I'm not going to place it here.

    
    JTextPane jTextPane = new JTextPane();
    
    MessageConsole console = new MessageConsole(jTextPane);
    /*
    This parameters are optional, but if you are looking for a solution with JTextPane it is because you need them, at least color.
    */
    console.redirectErr(Color.RED, null);
    console.redirectOut();
    
    //some event
    private void jButton1ActionPerformed(ActionEvent evt) {
        /*
        In this event I execute a function of my business.
        I put it in a thread so that it does not block the graphical interface.
        There are many calls to System.out.println() and System.err.println()
        */
        BusinessClass bc = new BusinessClass();
        Runnable runnable = () -> {
            bc.someBusinessFn();
        };
        thread = new Thread(runnable);
        thread.start();
    }
    
    //My main method
    public static void main(String args[]) {
            /* Create and display the GUI */
            EventQueue.invokeLater(() -> {
                new MyJFrame().setVisible(true);
            });
    }
    

    Edit

    Sorry, I did not realize that in the response similar to this, they had put the link to the MessageConsole class. I didn't see it and I also wanted to show my solution.

提交回复
热议问题