This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JTextArea - changing color of some words  RSS feed

 
Jeronimo Backes
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is possible to change the color and text formatting of some words of a text inside a JTextArea?

I made a little editor with that component, and that's the only thing I couldn't do yet.

I tried to change that class to inherit from JEditor pane, where I can colorize wathever I want with HTML. BUT, I wasn't able to get the funcionality that JTextArea provided: TabSize and RowHeaders that can show the line number (I wasn't able to retrieve the correct line height using html text... and I even had some trouble concerning caret positioning).

I tried to make a hack with the Highlighter class, but even changing the original source code from sun, I wasn't able to make some pieces of text appear with another color. In fact, they appear with the correct color, but behind the text.

Okay, I tried everything I could think of. Can someone give me a hand with that issue? That little thing caused enough pain.
 
Mark Van Tuyl
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only way I'm aware of that you could do that would be to draw the text in a Graphics area.
 
Jeronimo Backes
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, here's the next thing I'll try to do: override the paint(Graphics g) of JTextArea. It will surely work.

Thanks man.
 
Brian Cole
Author
Ranch Hand
Posts: 935
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jer´┐Żnimo Backes:
It is possible to change the color and text formatting of some words of a text inside a JTextArea?


Is there a reason you need to use JTextArea instead of JTextPane?


This code is an excerpt from this code. If you want to create your own editor with JTextPane, I recommend you take a look at chapter 22 of O'Reilly's Java Swing, 2nd ed.
(Disclaimer: I am the author.)

JTextArea ignores anything you do with setCharacterAttributes(), so
this approach only works with JTextPane.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!