Chapter 21. Styled Documents and JTextPane
In
the previous chapter, we introduced the classes and interfaces used
to represent textual models in Swing. In this chapter, we’ll
see how the Swing text model is extended to provide a simple
mechanism for working with text “styles,” greatly
simplifying the process of creating a powerful text editor. Once
we’ve defined these extensions to the text model, we’ll
look at the JTextPane
class and see how it takes
advantage of this model. At the end of the chapter, we’ll look
at a detailed example of a simple editor that shows the power of
styles.
Style
If you’ve ever worked with a reasonably powerful word processor, you’re probably already familiar with the concept of a style. A style is basically just a collection of attributes that describes how something should look. For example, as I sit here writing this book, the text I’m entering into my word processor looks a certain way because of the paragraph style (Body) and character style (Default) I have selected. To produce the heading just before this paragraph, I could have typed “Style,” selected the text, changed the font to Bodoni BT, changed the font size to 18, and toggled on the italics button. Thankfully (believe me!), I didn’t have to do all that. All I had to do was click somewhere within the text and use a menu to select the HeadA style, which encapsulates all of the properties described above (not to mention more interesting things, like the fact that the next paragraph should be ...
Get Java Swing now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.