Views

In our discussion of how Swing represents styled text, we haven’t mentioned how it is actually drawn on the screen. That’s where the View classes come in. They form most of the V part of the MVC architecture for text components and are responsible for rendering the text.

The way this works is a tree of View objects is created from the Document’s Element tree. (Examples of this are shown in Figure 22-11.) For DefaultStyledDocuments in a JTextPane, the View tree is modeled closely on the structure of the Element tree, with almost a one-to-one mapping from Elements to Views. A PlainDocument in a JTextArea is handled more simply, with a single View object that paints the entire Element tree.

View trees created from Element trees

Figure 22-11. View trees created from Element trees

Notice that the View trees have a root View above what could be considered the “natural” root. This was done to ease the implementation of the other View classes, which can now all assume that they have a non-null parent in the View tree. So that each child doesn’t have to register as a DocumentListener, the root View also takes care of dispatching DocumentEvents to its children. The actual type of the root View is a package-private inner class. (You are free to create a View tree with any root you like, so this does not always need to be the case. The implementations of the TextUI.getRootView( ) method that Swing provides do return a package-private ...

Get Java Swing, 2nd Edition 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.