How to Send Colored Text to JTextArea Using execToTextArea
Published: 2026-06-07
Google AdSense 广告位 (待申请通过后开启)
The execToTextArea() utility method allows command-line output to be streamed directly into a custom JTextArea component.
Features:
• Execute Linux commands asynchronously
• Display output in real time
• Support colored text rendering
• Keep the Swing UI responsive
• Easy integration into terminal-like applications
import javax.swing.SwingUtilities;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public static void execToTextArea(final String s, final com.util.JTextArea textArea) {
// Create an independent new thread to execute the Linux command so it never freezes the GUI
new Thread(new Runnable() {
@Override
public void run() {
String[] cmds = { "/bin/sh", "-c", s };
try {
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.environment().put("TERM", "xterm-256color");
pb.redirectErrorStream(true);
Process pro = pb.start();
// Specify UTF-8 encoding to prevent Chinese paths or command outputs from turning into garbled text
BufferedReader reader = new BufferedReader(
new InputStreamReader(pro.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
// 1. Core real-time cleanup: Handle inline overwriting behavior from physical terminals (e.g., \r)
if (line.contains("\r")) {
line = line.substring(line.lastIndexOf("\r") + 1);
}
// 2. Filter out useless non-color cursor control codes
line = line.replaceAll("\u001B\\[[0-9;]*[KkHhGgA-DzZ]", "");
line = line.replaceAll("\u001B\\[2J", "");
line = line.replaceAll("\u001B\\([A-B]", "");
// Final cleaned line text passed to the parser (Note: JTextArea already handles line-by-line parsing internally)
final String cleanedLine = line;
// 3. Crucial step: Switch back to the Swing Event Dispatch Thread to safely refresh the UI
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Call your previously modified append method which includes inline ANSI color parsing
textArea.append(cleanedLine);
}
});
}
reader.close();
pro.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}).start(); // Start the asynchronous thread
}