I need to know how to do this:
Let's say: I have a code in the jtextArea like this,
LOAD R1, 1 DEC R1 STORE M, R1 ADD R4, R1,8
I wanted to change the color of LOAD, DEC, STORE and ADD to color BLUE R1, R4 to color green M to RED numbers to ORANGE
How to change the color of this text? These text were from notepad or can be directly type to the textArea.
Thank you in advance.
For some basic coloring (the only thing you can do with JTextArea) you can change the background and foreground colors to something like this, but this will color all text of course:
The result you get:
Use can either use a JEditorPane with HTML or write a custom Document that colors elements.
Just another alternative. For the theory, see other answers.
This one creates attributes when adding text, instead of deriving the style like in the answer of nIcE cOw. The functionality is the same, as the pane will merge the attributes with any previously used attributes.
[Edit] changed back to
insertString
instead ofreplaceSelection
because the latter fails when the pane is not editableYou can't have different characters in different colors in a JTextArea (at least not without some complex hackery). Use a JTextPane or JEditorPane instead. Then you can access its
StyledDocument
:EDITED: changed to directly calling
getStyledDocument
, instead of casting the result of getDocument()Call
setCharacterAttributes
on theStyledDocument
to change the colors of individual characters or substrings.Just another alternative. For the theory, see other answers.
This one uses preconfigured styles as fields. Watch out when exposing these fields as they are, ehm, mutable.
[Edit] changed back to
insertString
instead ofreplaceSelection
because the latter fails when the pane is not editableJTextArea
is meant to entertainPlain Text
. The settings applied to a single character applies to whole of the document inJTextArea
. But withJTextPane
orJEditorPane
you have the choice, to colour yourString Literals
as per your liking. Here with the help of JTextPane, you can do it like this :here is the Output :