【问题标题】:System.setOut with PipedOutputStreamSystem.setOut 与 PipedOutputStream
【发布时间】:2013-11-27 15:23:13
【问题描述】:

我已经使用 JTextArea 开发了一个小型控制台。我阅读了一些教程并知道了一些东西。但我仍然有一个问题。这是我的代码。

public class Console extends JFrame {

    public Console() throws IOException {
        setSize(492, 325);
        setLayout(new BorderLayout());
        setDefaultCloseOperation(3);
        setVisible(true);

        final JTextArea area = new JTextArea();
        add(area, BorderLayout.CENTER);

        JButton button = new JButton("test");
        add(button, BorderLayout.EAST);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Test with Button Click.."); // this is not print in textarea.
            }
        });

        final PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream(pis);
        System.out.println("Test Before setOut.");
        System.setOut(new PrintStream(pos, true));

        System.out.println("Test After setOut."); // this is printed in my textarea.
        new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() throws Exception {
                Scanner scan = new Scanner(pis);
                while (scan.hasNextLine())
                    area.append(scan.nextLine());
                return null;
            }

        }.execute();

    }

    public static void main(String[] args) throws Exception {
        new Console();
    }
}

这是我的输出..

单击按钮时,System.out.println 无法与 textarea 一起使用。我不知道我做错了什么。

【问题讨论】:

    标签: java swing console swingworker


    【解决方案1】:

    当您调用SwingWorker.execute() 时,它只运行一次。所以在这里,它读取第一个println(),到达文档的末尾,然后停止运行。

    更好的解决方案是实现您自己的OutputStream 并将其write() 方法附加到文本区域,使用SwingUtilities.invokeLater() 确保这在AWT 线程上完成。

    大概是这样的:

    class TextAreaOut extends OutputStream implements Runnable {
        JTextArea text;
        String buffer = "";
    
        TextAreaOut(JTextArea text) {
            this.text = text;
            System.setOut(new PrintStream(this));
        }
    
        @Override
        public synchronized void run() {
            text.append(buffer);
            buffer = "";
        }
    
        @Override
        public synchronized void write(int b) throws IOException {
            if(buffer.length() == 0) {
                SwingUtilities.invokeLater(this);
            }
            buffer += (char)b;
        }
    }
    

    【讨论】:

    • 还有其他解决方案吗..?
    【解决方案2】:

    我发现使用管道流令人困惑。您可以查看Message Console 了解不同的方法。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多