Java Tips Weblog

  • Blog Stats

    • 1,256,773 hits
  • Categories

  • Archives

Text Utilities

Posted by Rob Camick on October 26, 2008

The JDK already supports a class dedicated to Text Utilities. Although you may have missed it because the class is called Utilities. The class is full of static methods to help you work with text components. Of course a few more methods would never hurt.

The RXTextUtilities class provides a few more static methods that you may find usefull, especially if you are building a simple text editor and want information for a status bar:

  • centerLineInScrollPane
  • getColumnAtCaret
  • getLineAtCaret
  • getLines
  • gotoStartOfLine
  • gotoFirstWordOnLine
  • getWrappedLines

Although the above methods use a JTextComponent as a parameter, the methods have only been tested using a JTextArea and JTextPane with plain text. I have no idea what results you would get using a text component with HTML.

Also, the getColumnAtCaret() method only makes sense when using a Monospaced font.

Many of the methods take advantage of the Element structure used by the Document of the text component to find the required information.

Get The Code

RXTextUtilities.java

Related Reading

The Element Interface
Java API: javax.swing.text.Utilities

About these ads

6 Responses to “Text Utilities”

  1. Adam said

    Helpful indeed, cheers

  2. Graham said

    Thanks so much Rob for making available your utilities. I’m relatively new to Java coding and learn much more from working examples than trial & error. Your method centerLineInScrollPane has no given me a much better understanding of how to use setViewPosition.

  3. jnorthr said

    thanx for your efforts. it’s a joy to find something so easy to integrate into a new codebase without re-inventing the wheel !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 96 other followers

%d bloggers like this: