简体   繁体   中英

Showing my printed lines in Frame

I am writing a monopoly game. In game at some points I print "your balance is 1500" or "you diced 12" kind of things. I want to transfer this printed things into my frame with using textarea. I created text area I can see it in my application. But how am I going to see my console in that text area? Thanks in advance.

public class Monopoly {
    public Monopoly() {
        JFrame frame = new JFrame("Monopoly");
        Game g = new Game();
        Board b = new Board(g);
        frame.setSize(1368, 750);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(b);
        JTextArea textArea = new JTextArea();
        textArea.setBounds(700, 0, 6, 200);
        b.add(textArea);
        frame.setVisible(true);
    }
}

Try this:

private void updateTextArea(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        textArea.append(text);
      }
    });
  }

  private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
      @Override
      public void write(int b) throws IOException {
        updateTextArea(String.valueOf((char) b));
      }

      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        updateTextArea(new String(b, off, len));
      }

      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
  }

Source

You can make textArea a private instance field in your class and initialize it in your constructor:

private JTextArea textArea;

public Monopoly() {
    // ...
    textArea = new JTextArea();
    // ...
}

Then, whenever you need to display something, instead of printing to the console via System.out , use the JTextArea's append method instead.

textArea.append("Your balance is 1500\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM