Java Console JPanel

Deadly 提交于 2019-12-11 03:29:51

问题


Hello Is it possible to draw in a JPanel what the java console is returning ? have you got a tutorial to follow ? thanks sw


回答1:


I can't remember where I found this, but I have outputted the output stream to a JTextArea held in a JPanel using a class I call TextAreaOutputStream:

import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaOutputStream extends OutputStream {

    private final JTextArea textArea;
    private final StringBuilder sb = new StringBuilder();
    private String title;

    public TextAreaOutputStream(final JTextArea textArea, String title) {
        this.textArea = textArea;
        this.title = title;
        sb.append(title + "> ");
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
    }

    @Override
    public void write(int b) throws IOException {

        if (b == '\r')
            return;

        if (b == '\n') {
            final String text = sb.toString() + "\n";
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    textArea.append(text);
                }
            });
            sb.setLength(0);
            sb.append(title).append("> ");
        }

        sb.append((char) b);
    }
}

I then re-direct the standard output Stream to this object as Alex mentions in his answer above.




回答2:


First read from the console. To do this use System.setOut(). Use ByteOutputStream, write there and read from their. You will get what your program prints to it system out. Now use either TextArea or JScrollPane to present the text.




回答3:


Create a subclass of FilterOutputStream to echo everything to a JTextArea.

class Echo extends FilterOutputStream {

    private final JTextArea text;

    public Echo(OutputStream out, JTextArea text) {
        super(out);
        if (text == null) throw new IllegalArgumentException("null text");
        this.text = text;
    }

    @Override
    public void write(int b) throws IOException {
        super.write(b);
        text.append(Character.toString((char) b));
        // scroll to end?
    }

    // overwrite the other write methods for better performance
}

and replace the standard output:

    JTextArea text = new JTextArea();
    System.setOut(new PrintStream(new Echo(System.out, text)));



回答4:


The Message Console provides a few more options that might interest you.



来源:https://stackoverflow.com/questions/4422642/java-console-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!