contentPane : Java Glossary
When Swing’s JFrame class got too large it was broken into pieces.
Unfortunately, the designers of Swing decided not to mask that change from the users with a facade design pattern. For some functions, such as adding a JComponent, you no longer use JFrame.add, but instead you must first
get the associated Container object of the JFrame with
JFrame.getContentPane(), and add to that. If you screw up, and accidentally use
JFrame.add(), you won’t find out until run time, and even then the code often
just quietly fails without an error message. To keep you on your toes, some Components
have contentPanes and some do not. in particular JPanel does
not. You add to a JPanel the some was as before.
Sun saw the error of their ways and now permits you to use JFrame. add and brethren safely in Java 1.5+. However, now you have a
new problem, namely running code developed on 1.5 that works fine on 1.5+ but fails on 1.4, even when you target
The following methods should normally be used on the contentPane, not the JFrame itself.
- Note there is no such class as ContentPane. JFrame.
getContentPane returns a vanilla Container.
- JApplet, JDialog, JFrame,
JInternalFrame, JOptionPane and JWindow all suffer from this contentPane gotcha.
- If you do a jFrame.setBackground( Color. black ), you won’t see the effect, except when resizing.
Then you will see the black frame behind the contentPane only briefly. You must do a
contentPane. setBackground( Color.black ) instead to get a permanent black background. Similarly
use contentPane for setForeground and setFont.
- revalidate only works on JComponents, not a
Container like contentPane.