What is a lightweight component?

Tim Rohaly

Before talking about lightweight components, it is necessary to discuss the concept of Java peers. When instantiating any of the AWT component classes, e.g. a java.awt.Button, the system actually asks the native environment to create the component. This ensures the user sees the native look-and-feel and the component acts like the native control. The native code that provides this look-and-feel is called a peer; each platform has its own set of peers. A Java button appears and acts as a Windows button when run under Windows, as a Macintosh button when run under Macintosh, and as a Unix button when run under Unix. The FAQ found at http://www.jguru.com/jguru/faq/view.jsp?EID=11353 discusses the concept of peers in more detail.

While in practice this sounds great, there are problems because not all native controls respond similarly to the same events. This can result in a Java program exhibiting different behavior under different Java AWT environments. To overcome this problem, you must use components written entirely in Java. That is, components that do not have a native peer. These are called lightweight components. Swing provides a set of pure Java lightweight components, ensuring better cross-platform compatibility. (Or at least ensuring that any bugs are the same bugs on all platform - a very important feature!)

A lightweight component is one that subclasses java.awt.Component (or java.awt.Container) directly - implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer. Lightweight components can be more efficient at utilizing system resource, they can be transparent, and they do not have to be rectangular (all of which are limitations when working with components that have a peer). For instance, if you are creating lots of panels to help layout components, you can create a LightweightPanel class that subclasses Container to use instead. This would allow you to use the LayoutManager on your panel but not require the overhead of managing all the heavyweight peers that would be created with each java.awt.Panel.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact