Java GUI: about getContentPane( ) method and content

早过忘川 提交于 2020-01-12 01:47:23

问题


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.


回答1:


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).




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16744152/java-gui-about-getcontentpane-method-and-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!