views:

36

answers:

2

I'm trying and failing to understand how to use Java's text editor components to colorize text as you insert it. I don't want or need a fully featured syntax highlighting library.

Basically, I have a JTextField (or some other JText... component), and a list of words. I want any words in the field that appear in the list to be red, and the rest of the words be green. So for example, if "fire" is in the list, "fir" would appear green and "fire" would appear red.

I've tried using a JTextPane and a DefaultStyledDocument, using a KeyListener to go over the text in the document and using AbstractStyledDocument.replace to replace the existing words with versions that have the correct attributes. This didn't do anything. What am I doing wrong?

+1  A: 

Neither JTextPane nor JTextField isn't able to present formatted text, i.e text having more than one format. For text-editor-like capabilities like you'd find in WordPad or HTML, the component to use is the JEditorPane or its descendant, JTextPane.

The simplest thing you can do is set the ContentType of the JEditorPane to "text/html" and simply set its text to a string containing HTML. The Java structured text components are surprisingly competent with HTML; you can display tables and/or DIVs, and there is support for much of CSS2. Simplest to do your styles inline, but you can even do external style hrefs.

If you want to get fancy programmatically, you can access the DocumentModel and create text from spans of text each having their own formatting. The DocumentModel works essentially like a programmable text editor.


EDIT: Re-reading your question, I see my answer doesn't quite address it. Since you want multi-colored text JEditorPane is your only option; but rather than just piping in pre-colored text via HTML or such, you'll have to put a listener on your document model to catch changes introduced when you type; and after every document change you'll want to examine the text (again from the Document model) for text that should or should not be highlighted, and you'll want to apply formatting to certain runs of text.

There are devils in the details, but this should get you started.

Carl Smotricz
The difficulty is that I need to do this colouration on the fly as the user types in the text. So I don't as much need to create text as colourize it as I go along.
Zarkonnen
The stuff from my EDIT (south of the horizontal line) should help you. Listening on the model lets you respond to any new/changed text by colorizing it as you see fit.
Carl Smotricz
+1  A: 

This should help you http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords2.html

eugener