Java - Redirecting system.out.println to a JLabel

user1880046 picture user1880046 · Dec 15, 2012 · Viewed 9.5k times · Source

I want to redirect a sytem.out.println to a JLabel in another class.

I have 2 classes, NextPage and Mctrainer.

NextPage is basically just a Jframe (The gui for my project), and I have created a Jlabel in Nextpage using this code;

public class NextPage extends JFrame {

    JLabel label1; 

    NextPage() {
        label1 = new JLabel();
        label1.setText("welcome");
        getContentPane().add(label1);

This is the code for Mctrainer:

public class Mctrainer {

    JLabel label1;

    Mctrainer() {
        HttpClient client2 = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://oo.hive.no/vlnch");
        HttpProtocolParams.setUserAgent(client2.getParams(),"android");
        try {
            List <NameValuePair> nvp = new ArrayList <NameValuePair>();
            nvp.add(new BasicNameValuePair("username", "test"));
            nvp.add(new BasicNameValuePair("password", "test"));
            nvp.add(new BasicNameValuePair("request", "login"));
            nvp.add(new BasicNameValuePair("request", "mctrainer"));
            post.setEntity(new UrlEncodedFormEntity(nvp));

            HttpContext httpContext = new BasicHttpContext();

            HttpResponse response1 = client2.execute(post, httpContext);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            } 
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }

Mctrainer basically just prints out JSON data from a server using system.out.println. I want to redirect it to show up in the JLabel in my GUI (NextPage) instead of console. Any suggestions on how to do this?

Answer

You need only to change the default output...

Check out System.setOut(printStream)

public static void main(String[] args) throws UnsupportedEncodingException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(bos));
    System.out.println("outputing an example");
    JOptionPane.showMessageDialog(null, "Captured: " + bos.toString("UTF-8"));
}

Also, your question is pretty similar to this other one, so I could adapt this accepted answer to work with JLabel

public static void main(String[] args) throws UnsupportedEncodingException
{
    CapturePane capturePane = new CapturePane();
    System.setOut(new PrintStream(new StreamCapturer("STDOUT", capturePane, System.out)));

    System.out.println("Output test");

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(capturePane);
    frame.setSize(200, 200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    System.out.println("More output test");
}

public static class CapturePane extends JPanel implements Consumer {

    private JLabel output;

    public CapturePane() {
        setLayout(new BorderLayout());
        output = new JLabel("<html>");
        add(new JScrollPane(output));
    }

    @Override
    public void appendText(final String text) {
        if (EventQueue.isDispatchThread()) {
            output.setText(output.getText() + text + "<br>");
        } else {

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    appendText(text);
                }
            });

        }
    }        
}

public interface Consumer {        
    public void appendText(String text);        
}


public static class StreamCapturer extends OutputStream {

    private StringBuilder buffer;
    private String prefix;
    private Consumer consumer;
    private PrintStream old;

    public StreamCapturer(String prefix, Consumer consumer, PrintStream old) {
        this.prefix = prefix;
        buffer = new StringBuilder(128);
        buffer.append("[").append(prefix).append("] ");
        this.old = old;
        this.consumer = consumer;
    }

    @Override
    public void write(int b) throws IOException {
        char c = (char) b;
        String value = Character.toString(c);
        buffer.append(value);
        if (value.equals("\n")) {
            consumer.appendText(buffer.toString());
            buffer.delete(0, buffer.length());
            buffer.append("[").append(prefix).append("] ");
        }
        old.print(c);
    }        
}