I'm curious... Why does the JComponent.isLightweightComponent(Component c) method return false when passing swing components such as JLabel, JButton, etc.? According to everything that I have read, these components should be lightweight.
Does this indicate that they are in fact heavyweight (definitely shouldn't be)?
Or is the isLightweightComponent() method broken in some way?
Or am I not understanding something about the isLightweightComponent() method?
Try the following code to see what I mean...
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingLightweightTest {
public static void main(String[] args) {
// why do swing components show that they not Lightweight?
// does this mean that they are Heavywight?
// or is the .isLightweightComponent() method broken?
JLabel jLabel = new JLabel();
testLightweight(jLabel);
JButton jButton = new JButton();
testLightweight(jButton);
JPanel jPanel = new JPanel();
testLightweight(jPanel);
}
private static void testLightweight(JComponent comp) {
String isIsnot;
isIsnot = JComponent.isLightweightComponent(comp) ? "IS ": "IS NOT ";
System.out.println(comp.getUIClassID() + " \t" + isIsnot + "a lightweight component");
}
}
it returns the following:
LabelUI IS NOT a lightweight component
ButtonUI IS NOT a lightweight component
PanelUI IS NOT a lightweight component
The method
isLightweightComponent
is actually not checking to see if the component itself is lightweight, but rather it checks if the component's "peer" is lightweight. (As such, perhaps this method isn't named well?)Internally the method checks if the component's peer is an instance of
LightweightPeer
:c.getPeer() instanceof LightweightPeer
. And it looks like onlyNullComponentPeer
andNullEmbeddedFramePeer
even implement this interface. Also, the JavaDoc forisLightweightComponent
has this to say:From what I can gather, peers are a sort of behind-the-scenes means of picking up native OS events and routing them to components.
Update
Upon further investigation I have discovered that before a component is made visible it has no peer (
c.getPeer()
returns null) and thus the checkc.getPeer() instanceof LightweightPeer
will returnfalse
(seemingly indicating that the component is not lightweight which is misleading). Once a component has been made visible it will be assigned a peer (my testing shows that JLabel, for instance, gets a NullComponentPeer instance as its peer) and thus will return correct information from a call toisLightweightComponent
.In summary:
isLightweightComponent
is checking only if a component's peer is an instance ofLightweightPeer
, and it returnsfalse
(instead of returningnull
or throwing an exception) when it can't actually determine whether the peer is lightweight or not.