Chapter 3. Swing Component Basics

The previous chapter showed you how easy it was to create some impressive-looking programs with Swing components. Now it’s time to dig in a little deeper. We begin this chapter by presenting an overview of Action, a key class in Swing, and briefly discussing ChangeEvent and PropertyChangeEvent, two central event classes in Swing. Finally, we spend the remainder of the chapter introducing the JComponent class, the heart and soul of all Swing components.

Understanding Actions

Actions are a popular addition to Swing. An action allows a programmer to bundle a commonly used procedure and its bound properties (incl uding an image to represent it) into a single class. This construct comes in handy if an application needs to call upon a particular function from multiple sources. For example, let’s say that a Swing programmer creates an action that saves data to disk. The application could then invoke this action from both the Save menu item of the File menu, and the Save button on a toolbar. Both components reference the same action object, which performs the task of saving the data. If the save function is disabled for some reason, this property can be set in the action as well. The menu and toolbar objects are automatically notified that they can no longer save any data, and can relay that information to the user.

Actions and Containers

Swing containers, such as JMenu, JPopupMenu, and JToolBar, can each accept action objects with their add() methods. ...

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.