In this piece of code:
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
I can see it makes a new label and adds it to the JFrame
object frame
. But I want to understand what does getContentPane()
do, and why do I need it?
I read this API but I still didn't understand.
Every Swing top level container (and JInternalFrame) has what's called a JRootPane
. This is responsible for actually managing the overall layout of the window.
The root pane has a number of layers, one of which is the content pane. When you add something to a frame (since Java 5 I think), it is automatically added to the content pane for you, before this, you had to call getContentPane().add(...)
yourself
Take a look at How to use RootPanes
Every JPanel
is a container, so either add it to a panel then add it to the container or directly use add(component)
or use the getContentPane().add
method. Both add the component to the container in Java 7 ( I don't know if version 6 has a problem with this or not ).
A container has several layers in it. You can think of a layer as a transparent film that overlays the container . In Java Swing, the layer that is used to hold objects is called the content pane . Objects are added to the content pane layer of the container .
The getContentPane() method retrieves the content pane layer so that you can add an object to it. The content pane is an object created by the Java run time environment . You do not have to know the name of the content pane to use it. When you use getContentPane()
, the content pane object then is substituted there so that you can apply a method to it.
A JFrame is the headcomponent which is put together with other subcomponents. With getContentPane() gets the component that represents the contents of a graphical user interface. A JMenuBar for example is placed in another area next to the contentPane of a frame.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.