use*_*111 14 java swing jtextarea
我试图在java中的textArea中获取控制台的内容.
例如,如果我们有这个代码,
class FirstApp {
public static void main (String[] args){
System.out.println("Hello World");
}
}
Run Code Online (Sandbox Code Playgroud)
我想将"Hello World"输出到textArea,我必须选择什么actionPerformed?
我找到了这个简单的解决方案:
首先,您必须创建一个类来替换标准输出:
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
// keeps the textArea up to date
textArea.update(textArea.getGraphics());
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您按以下方式替换标准:
JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);
Run Code Online (Sandbox Code Playgroud)
问题在于所有输出将仅在文本区域中显示。
带有示例的源代码:http : //www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea
您必须重定向System.out到 的自定义、可观察子类PrintStream,以便添加到该流的每个字符或行都可以更新 textArea 的内容(我猜,这是一个 AWT 或 Swing 组件)
PrintStream可以使用 a 创建实例,ByteArrayOutputStream它将收集重定向的输出System.out
| 归档时间: |
|
| 查看次数: |
50521 次 |
| 最近记录: |