Show data on JTextArea instead of console

I want to have a JTextArea that can work entirely instead of a console but I don't know how to do it!



source to share

2 answers

The solution to the problem is to redirect System.{in,out,err}

to JTextArea


  • Starting from System.out

    , it's pretty simple to redirect it to your component JTextArea

    using the System.setOut

    . In the example below, I did it using pipes and SwingWorker

    , but it's all fancy stuff to get a simple result for a swing component.

  • Emulation

    is a simulator, you need to redirect your keystrokes to

    using System.setIn

    . Again, in the example below, I've used pipes to get a more user-friendly interface. I also buffer the line (just like a "regular" console) until you hit enter. (Note that, for example, the arrow keys won't work, but it doesn't take much work to get it to handle / ignore as well.)

The text in the screenshot below was received by several calls to the "normal" method System.out.print..

, and then waiting for input

with Scanner



public static JTextArea console(final InputStream out, final PrintWriter in) {
    final JTextArea area = new JTextArea();

    // handle "System.out"
    new SwingWorker<Void, String>() {
        @Override protected Void doInBackground() throws Exception {
            Scanner s = new Scanner(out);
            while (s.hasNextLine()) publish(s.nextLine() + "\n");
            return null;
        @Override protected void process(List<String> chunks) {
            for (String line : chunks) area.append(line);

    // handle ""
    area.addKeyListener(new KeyAdapter() {
        private StringBuffer line = new StringBuffer();
        @Override public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (c == KeyEvent.VK_ENTER) {
            } else if (c == KeyEvent.VK_BACK_SPACE) { 
                line.setLength(line.length() - 1); 
            } else if (!Character.isISOControl(c)) {

    return area;


And an example method main


public static void main(String[] args) throws IOException {

    // 1. create the pipes
    PipedInputStream inPipe = new PipedInputStream();
    PipedInputStream outPipe = new PipedInputStream();

    // 2. set the and System.out streams
    System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));

    PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);

    // 3. create the gui 
    JFrame frame = new JFrame("\"Console\"");
    frame.add(console(outPipe, inWriter));
    frame.setSize(400, 300);

    // 4. write some output (to JTextArea)
    System.out.println("Hello World!");

    // 5. get some input (from JTextArea)
    Scanner s = new Scanner(;
    System.out.printf("got from input: \"%s\"%n", s.nextLine());




Take a look at Simple Java Console (Swing based)



All Articles