4

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1880046
  • 59
  • 1
  • 1
  • 2
  • 1
    *"in another class."* Whenever I see that phrase, it makes me wonder if the asker has any idea of how to program in an OO language. It should be a non-issue by the stage you start programming a GUI. If it is an issue, stop trying to program GUIs for a while & return to the basics for some revision. – Andrew Thompson Dec 15 '12 at 15:54
  • I just thought it'd mention it in case it mattered regarding redirecting from system.out.println. – user1880046 Dec 15 '12 at 15:59
  • This question is similar to: http://stackoverflow.com/questions/12945537/how-to-set-output-stream-to-textarea – Polyana Fontes Dec 15 '12 at 16:07
  • Using System.out.println for any reason other than immediate debugging is bad in itself, why do you even consider integrating it further into GUI. If you want to log something use a logging framework, or for your case look at the Observer design pattern. – ali köksal Dec 15 '12 at 16:28

1 Answers1

7

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);
    }        
}
Community
  • 1
  • 1
Polyana Fontes
  • 3,156
  • 1
  • 27
  • 41
  • @ José Any chance you could give me an example? I've spent the last 4 hours trying to redirect it, without any luck so far. – user1880046 Dec 15 '12 at 16:04
  • 1
    Here's an example: http://viralpatel.net/blogs/java-reassign-standard-output-error/ – Viral Patel Dec 15 '12 at 16:06
  • @José Roberto Araújo Júni this idea talking about JTextArea / JTextPane :-) – mKorbel Dec 15 '12 at 16:06
  • @ViralPatel In that link, it says, PrintStream ps = new PrintStream("C:/sample.txt"); System.setOut(ps); So in my code, I tried PrintStream ps = new PrintStream("NextPage.label1"); System.setOut(ps); System.out.println(line); But it didn't work. Am I getting close to solving it, or am I far off? – user1880046 Dec 15 '12 at 16:14
  • @José That code works, but it opens a new window (JTextArea or something, I'm not 100% sure) instead of redirecting it to the actual label, as in, inside the JFrame. But thank you so much! – user1880046 Dec 15 '12 at 16:17
  • @mKorbel but the solution is the same, I edited my answer adapting the answer in the other question to work with JLabel – Polyana Fontes Dec 15 '12 at 16:24
  • @user1880046 In the first example I only showed how to capture the System.out, I've just edited the answer to show more details in what you can do – Polyana Fontes Dec 15 '12 at 16:25
  • for some reason this example shows "
    " as text instead of making line break
    – Shpytyack Artem Nov 04 '14 at 12:02