Java “Container c=getContentPane();”的目的是什么?在摇摆?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/708302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:35:25  来源:igfitidea点击:

What is the purpose of "Container c=getContentPane();" in Swing?

javaswing

提问by jaffar

import java.awt.*;
import javax.swing.*;
public class 
import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
import javax.swing.event.*;
/*<applet code="JT.class" width=200 height=300>
</applet>*/

 

 

public class JT extends JApplet {
    JTree tree;
    JTextField box;
    Object nodeInfo;
    String node1;
    public void init() {
        Container c=getContentPane();
        c.setLayout(new BorderLayout());
        DefaultMutableTreeNode topNode=new DefaultMutableTreeNode("qiscet");
        DefaultMutableTreeNode cou=new DefaultMutableTreeNode("Courses");
        DefaultMutableTreeNode mca=new DefaultMutableTreeNode("MCA");
        DefaultMutableTreeNode mba=new DefaultMutableTreeNode("MBA");
        DefaultMutableTreeNode tech=new DefaultMutableTreeNode("B.tech");
        topNode.add(cou);
        cou.add(mca);   
        cou.add(mba);
        cou.add(tech);
        DefaultMutableTreeNode manage=new DefaultMutableTreeNode("Management");
        DefaultMutableTreeNode ac=new DefaultMutableTreeNode("Accounts");
        DefaultMutableTreeNode sp=new DefaultMutableTreeNode("Sports");
        DefaultMutableTreeNode lib=new DefaultMutableTreeNode("Library");
        topNode.add(manage);
        manage.add(ac); 
        manage.add(sp);
        manage.add(lib);
        tree=new JTree(topNode);
        c.add(tree,BorderLayout.NORTH);
        box=new JTextField("",80);
        c.add(box,BorderLayout.SOUTH);
    }
}

My question is without using "Container c=getContentPane();" i am getting correct output .How it is possible?What is the reason for this?

我的问题是不使用“Container c=getContentPane();” 我得到了正确的输出。怎么可能?这是什么原因?

回答by TofuBeer

To begin with Swing made you use getContentPane() for things like add() and setLayout() to make you realize that there were different layers. After a while I guess they conceded that it was a pain so they had the getContentPane() called internally so you didn't have to anymore.

Swing 开始让您使用 getContentPane() 来处理诸如 add() 和 setLayout() 之类的事情,让您意识到存在不同的层。过了一会儿,我猜他们承认这很痛苦,因此他们在内部调用了 getContentPane(),因此您不必再这样做了。

This was changed in JDK 1.5:

这在 JDK 1.5 中有所改变

Lastly, after seven years, we've made jFrame.add equivalent to jFrame.getContentPane().add()

最后,七年后,我们使 jFrame.add 等同于 jFrame.getContentPane().add()

And here is a link to the rationale behind the original reason.

这是原始原因背后的基本原理的链接。