简体   繁体   English

Java GUI:关于getContentPane()方法和内容

[英]Java GUI: about getContentPane( ) method and content

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 . 我可以看到它生成一个新标签并将其添加到JFrame对象frame But I want to understand what does getContentPane() do, and why do I need it? 但我想了解getContentPane()做了什么,为什么需要它呢?

I read this API but I still didn't understand. 我读了这个API,但我仍然不明白。

Every Swing top level container (and JInternalFrame) has what's called a JRootPane . 每个Swing顶级容器(和JInternalFrame)都有一个叫做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 当您向框架添加内容时(我认为是Java 5),它会自动添加到内容窗格中,在此之前,您必须调用getContentPane().add(...)自己getContentPane().add(...)

Take a look at How to use RootPanes 看看如何使用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. 每个JPanel都是一个容器,所以要么将它添加到面板然后将其添加到容器中,要么直接使用add(component)或使用getContentPane().add方法。 Both add the component to the container in Java 7 ( I don't know if version 6 has a problem with this or not ). 两者都将组件添加到Java 7中的容器中( 我不知道版本6是否存在此问题 )。

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 . 在Java Swing中,用于保存对象的图层称为内容窗格 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. getContentPane()方法检索内容窗格层,以便您可以向其添加对象。 The content pane is an object created by the Java run time environment . 内容窗格是Java运行时环境创建的对象。 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. 当您使用getContentPane() ,内容窗格对象将替换在那里,以便您可以将方法应用于它。

A JFrame is the headcomponent which is put together with other subcomponents. JFrame是与其他子组件放在一起的headcomponent。 With getContentPane() gets the component that represents the contents of a graphical user interface. 使用getContentPane()获取表示图形用户界面内容的组件。 A JMenuBar for example is placed in another area next to the contentPane of a frame. 例如,JMenuBar放置在框架的contentPane旁边的另一个区域中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM