Java Swing - O Reilly In this figure, we
Monday, December 31st, 2007Java Swing - O Reilly In this figure, we show what happens when a new JTree component gets created. The process is the same for any Swing component. 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)); } The updateUI() method asks the UIManager class (via its static getUI() method) for an appropriate UI delegate object. The UIManager consults an instance of UIDefaults (set up when the L&F was first installed) for the appropriate UI delegate. The UIDefaults object goes back to the component to get the UI class ID. In our JTree example, “TreeUI” will be returned. UIDefaults then looks up the Class object for the class ID. In this case, it finds the MetalTreeUI class. The static method createUI() is called (using reflection) on this UI delegate class. This static method is responsible for returning an instance of the UI delegate class. In some cases, a single instance is shared by all components. In other cases, a new instance is created each time. In this diagram, we show a new instance of MetalTreeUI being created and returned from createUI(). At last, the JTree has a UI delegate. The updateUI() method now calls setUI(). If a UI delegate was already installed (in this example, we’re creating a new component, so there is no delegate installed yet), setUI() would call uninstallUI() on the old delegate. setUI() now calls installUI() on the new UI delegate, passing in the component. The installUI() methods for different components do different things. Often (as shown here), installUI() is used to install listeners (allowing the UI delegate to keep track of changes made to the component), set defaults (e.g., fonts and colors), and add keyboard actions. Now that the new component has been associated with its UI delegate, it can use the delegate for all L&F-related operations. The JComponent base class delegates the following methods to its UI: paintComponent() (called by paint(); calls ui.update()) getPreferredSize() getMaximumSize() getMinimumSize() contains() The three size accessors only delegate to the UI if a value has not been explicitly set on the component itself via a call to setPreferredSize(), setMaximumSize(), or setMinimumSize(). Now let’s take a second look under the hood and see how the delegation of the painting process actually happens. The process in Figure 26.2 is pretty straight-forward. Figure 26.2. Swing painting delegation - 860
In case you need quality webspace to host and run your web applications, try our personal web hosting services.