In this blog post, I will introduce the layering of the JFrame window. JFrame inherit from frame, with JFrame, JDialog, JApplet are heavyweight components. If you don't figure out the hierarchy of a frame, you'll get an error when setting some special effects on the component, such as setting the background.
Frame Hierarchy Chart:
Each top-level container has a hidden intermediate container called root Pane. Root Pane manages the content Pane, Menu Bar, and other containers.
For example:
JFrame frame=New JFrame ("Test"); Frame.setbackground (color.red); Frame.setsize (a); Frame.setvisible (true);
When the program runs out, it will find that the background color is not set successfully because the content pane is drawn on top of root pane, so the content pane background is covered and therefore invisible.
You can hide the content pane:
JFrame frame=New JFrame ("Test"); Frame.getcontentpane (). setvisible (false); // setting content pane is not visible Frame.setbackground (color.red); Frame.setsize (a); Frame.setvisible (true);
This is not a good solution because the components set on the content pane are not visible,
Typically set to this:
JFrame frame=New JFrame ("Test"); JPanel p=new JPanel (); Frame.getcontentpane (). SetBackground (color.red); P.setopaque (false); // Set Transparent Frame.add (p); // Add some Components to P ... Frame.setsize (a); Frame.setvisible (true);
The P.setopaque (false) above indicates that the setting Jpane is transparent to the background, and only the background of the content panel can be seen with jpane background transparency.
The above modification is the background of the content panel, in fact, you can also modify the background of Jpane:
JFrame frame=New JFrame ("Test"); JPanel p=new JPanel (); Frame.add (p); P.setopaque (true); // set Opaque, default is opaque P.setbackground (color.red); // Set Background frame.setsize (a); Frame.setvisible (true);
It is important to note that the JPanel component is opaque, that is, Isopaque () returns True. However, some other components are transparent by default, such as JLabel
JFrame frame=New JFrame ("Test"); JPanel p=new JPanel (); JLabel Label=new JLabel ("Test"); Label.setopaque (true); // Set Opaque Label.setbackground (color.red); // Set Background p.add (label); Frame.add (p); Frame.setsize (a); Frame.setvisible (true);
"Java" details the hierarchy of JFRAME structures