ANSI colors in Java Swing text fields

Viewed 4704

Is there any simple way to parse Ansi colors in log files, and use it in text fields in Swing (JTextArea, JTextPAne,...)?

2 Answers

If youre JTextPane is non-editable then tim_yates method will not work, to improve upon his method I replaced his append method with

public void append(Color c, String s) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
    int len = getDocument().getLength(); 
    try {getDocument().insertString(len, s, aset);} 
    catch (BadLocationException e) {e.printStackTrace();}
}

This method seems to be much more robust and works in all of the cases I have tried, but I have not tested it in full

This method works by inserting colored text at the end of the document rather than replacing text that don't exist, which if it is non-editable just results in a repeated windows error sound which is quite annoying

Related