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

标签 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 中而不是控制台中。 有关如何执行此操作的任何建议?

最佳答案

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

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

关于Java - 将 system.out.println 重定向到 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893655/

相关文章:

java - synchronized Collection 的 toArray() 方法是同步的吗?

java - 如何创建像 sun.misc* 这样的受限包

java - 作为 Java 库提供的最好的免费 JavaScript 混淆器是什么?

java - 关闭 JFrame 时添加行为

java - 如何在 JTable 中显示带有 blob 的数据库表

java - 我如何获得 Java 12

java - 通过代码处理 JDialog,不要让用户关闭它

java - 能否将复选框和字符串合并到 JTable 的一个单元格中?

java - JLabel 从一个面板链接到另一个 JPanel

java - 通过按钮更改标签(Java/Swing 问题)