How Does It Work?

As you probably already know, each instance of a given Swing component uses a UI delegate to render the component using the style of the currently installed L&F. To really understand how things work, it helps to peek under the hood for a moment to see which methods are called at a few key points. The first point of interest is component creation time. When a new Swing component is instantiated, it must associate itself with a UI delegate object. Figure 26-2 shows the important steps in this process.[1]

UI delegate installation

Figure 26-2. UI delegate installation

In this figure, we show what happens when a new JTree component is created. The process is the same for any Swing component:

  1. First, the constructor calls updateUI( ). Each Swing component class provides an updateUI( ) method that looks something like this:

    public void updateUI( ) {
        setUI((TreeUI)UIManager.getUI(this));
    }
  2. The updateUI( ) method asks the UIManager class, described below, for an appropriate UI delegate object via its static getUI( ) method.

  3. The UIManager consults an instance of UIDefaults (set up when the L&F was first installed) for the appropriate UI delegate.

  4. The UIDefaults object goes back to the component to get the UI class ID. In this JTree example, "TreeUI" is returned.

  5. UIDefaults then looks up the Class object for the class ID. In this case, it finds the MetalTreeUI class.

  6. The static method createUI( ) is called (using ...

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.