How It All Works

The modularity of the Swing text components can be confusing. Fortunately, most of the time it doesn’t matter how it works as long as it does work. However, some understanding of what’s going on behind the scenes is necessary for what is to come in the next four chapters.

Let’s take a look at what needs to happen for a text component to be displayed. These behaviors describe the responsibilities of a JTextArea, but they are similar for other JTextComponents:

  • The text component retrieves its UI delegate from the L&F and installs it. For JTextArea, this might be javax.swing.plaf.basic.BasicTextAreaUI.

  • The UI delegate may set properties such as font, foreground, and selection color. The UI delegate may also set the caret, highlighter, InputMaps and ActionMap. The maps allow text components to respond to L&F-specific keyboard commands for actions such as cut/copy/paste, select-all, caret-to-end-of-line, page-down, and so on.

  • The UI delegate also instantiates an EditorKit. For JTextArea this might be javax.swing.text.DefaultEditorKit. Most of the Actions in the text component’s array come from the EditorKit.

  • If the text component’s constructor didn’t receive a Document, it creates one. JTextArea creates its Document (a PlainDocument) directly, but other text components delegate this to the EditorKit.

  • The Document is responsible for storing the component’s text content. It does this by breaking it into a hierarchy of one or more Elements. Each Element can hold part of the ...

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.