在框架中显示我打印的线条

Showing my printed lines in Frame

我正在写一个大富翁游戏。在游戏中的某些时候,我会打印 "your balance is 1500" 或 "you diced 12" 之类的东西。我想使用 textarea 将这些打印的东西转移到我的框架中。我创建了文本区域,我可以在我的应用程序中看到它。但是我怎样才能在那个文本区域看到我的控制台呢?提前致谢。

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

试试这个:

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

您可以在 class 中将 textArea 设为私有实例字段,并在构造函数中对其进行初始化:

private JTextArea textArea;

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

然后,每当您需要显示某些内容时,不要通过 System.out 打印到控制台,而是使用 JTextArea 的 append 方法。

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