Hello!
Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
private DefaultStyledDocument doc = new DefaultStyledDocument();
private JTextPane txtTest = new JTextPane(doc);
private Random random = new Random();
private void appendLong() throws BadLocationException {
String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
int start = doc.getLength();
doc.insertString(doc.getLength(), str, null);
int end = doc.getLength();
txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
}
private Color randomColor() {
int r = intRand(0, 255);
int g = intRand(0, 255);
int b = intRand(0, 255);
return new Color(r, g, b);
}
private int intRand(int low, int hi) {
return random.nextInt(hi - low + 1) + low;
}
As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
I can fix this problem by changing the insert line to this:
doc.insertString(doc.getLength()+1, str, null);
With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
I've tried in veign to hack that newline character away. For example:
if (doc.getLength() == 0) {
doc.insertString(doc.getLength(), str, null);
} else {
doc.insertString(doc.getLength()+1, str, null);
}
But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
I've also tried:
txtTest.setText(txtTest.getText()+str);
That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!