Hey, everyone, as you can see, first post. I'm just stumped. I've tried everything I can think of to highlight certain keywords as the user types in a non-CPU intensive manner in JTextPane with a StyledDocument. I'm almost sure there is a logical way that I cannot see, but here is what I have so far. The Patterns are already made and keywords are obviously found in there. When I run it, it highlights the first line perfectly. Second line, screws up by on (I'm guessing something with \n, but I really do not know). By the time I'm in the middle, if its already not on the keywords style (you can see what I mean in the code) as I type, the highlighting is way off. Thanks. Just a note - I'm 14, so if the answer is obvious, don't call me an idiot, etc.

private final Thread highlightKeywords = new Thread() {
			private Style keywords;

			@Override
			public void run() {
				for (final Pattern p : patterns) {
					final Matcher m = p.matcher(text.getText());
					while (m.find()) {
						if (keywords == null) {
							keywords = text.getStyle("Keywords");
						}
						doc.setCharacterAttributes(m.start(),
								(m.end() - 1) - m.start(), keywords, true);
					}
				}
			}
		};

Please help - it's urgent.

When / how often is this run?
Possibly there is a thread-related problem with your (possibly long-ish running) thread and the user (and you own) updates to the JTextPane on the Swing thread (EDT). Both are updating the document, but there's no synchronisation between them.
Maybe the fact that it starts OK but then gets worse is because your method's run time increases with the number of keywords in the document?

If you re-run exactly the same test multiple times do you get exactly the same errors, or do the exact form of the errors depend on how quickly you type?

Thanks for the help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.