4

我想将 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 中。关于如何做到这一点的任何建议?

4

1 回答 1

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

另外,您的问题与另一个问题非常相似,因此我可以调整这个公认的答案以使用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);
    }        
}
于 2012-12-15T15:58:17.550 回答