將列印流重新導向到TextArea
在Java 中,將資訊列印到控制台通常是使用System.out 串流完成的。然而,對於 GUI 應用程序,通常需要將此輸出重定向到指定的元件,例如文字區域。
Approach
要實現此目的,您可以利用 Java 的列印串流重新導向功能。操作方法如下:
建立 TextArea 物件:
建立自訂 PrintStream:
重定向System.out:
範例程式碼
以下範例程式碼示範了此方法(取代現有的setOutputStream() 方法):
<code class="java">private void setOutputStream() { // Create a TextArea object TextArea textArea = new TextArea(); // Create a custom PrintStream to redirect output to the TextArea aPrintStream = new PrintStream(new ByteArrayOutputStream()) { @Override public void print(String s) { // Append the output to the TextArea textArea.append(s); } }; // Redirect System.out to the custom PrintStream System.setOut(aPrintStream); // Add the TextArea to a TabbedPane on the GUI jTabbedPane1.add("Main", textArea); }</code>
透過實作此技術,所有後續的System.out 語句現在都會將其輸出列印到指定的TextArea。
以上是如何在 Java 中將 System.out 輸出重新導向到 TextArea?的詳細內容。更多資訊請關注PHP中文網其他相關文章!