Java - 将system.out.println重定向到JLabel

时间:2012-12-15 15:51:07

标签: java swing jlabel println system.out

我想将sytem.out.println重定向到另一个类中的JLabel。

我有2个课程,NextPage和Mctrainer。

NextPage基本上只是一个Jframe(我的项目的gui),我使用这个代码在Nextpage中创建了一个Jlabel;

public class NextPage extends JFrame {

    JLabel label1; 

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

这是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基本上只是使用system.out.println从服务器打印出JSON数据。 我想重定向它以显示在我的GUI(NextPage)中的JLabel而不是控制台。 有关如何做到这一点的任何建议吗?

1 个答案:

答案 0 :(得分:7)

您只需更改默认输出...

查看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"));
}

此外,您的问题与this other one非常相似,因此我可以调整this accepted answer以使用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);
    }        
}