为什么 JFrame 最初需要 getContentPane() 来添加组件
我知道,从 Java 1.5 开始,可以添加JFrame 的组件如下所示:
myFrame.add(myButton);
而不是:
myFrame.getContentPane().add(myButton);
为什么情况并非总是如此?
I know that, as of Java 1.5, one can add a component to a JFrame like this:
myFrame.add(myButton);
instead of:
myFrame.getContentPane().add(myButton);
Why wasn't this always the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 JFrame API 中所述,两者都做同样的事情:向 contentPane 添加一个组件。最近(也许是 Java 1.5?)Swing 添加了语法糖/便捷方法,允许您直接在 JFrame(或任何其他 Swing 顶级容器)上进行此调用,但您仍在添加到 contentPane。对于
remove(...)
和setLayout(...)
也是如此,如果您尝试通过myJFrame 设置 JFrame 的背景颜色,这一切就会变得非常清楚.setBackground(Color.green);
没有任何反应。正是因为这个原因,我对这个改变不太满意。那也是因为我一定是个脾气暴躁的老家伙。As is spelled out in the JFrame API, both do the same thing: add a component to the contentPane. It's just recently (Java 1.5 perhaps?) Swing added the syntactic sugar/convenience method to allow you to make this call directly on the JFrame (or any other Swing top-level container), but you're still adding to the contentPane. Same for
remove(...)
andsetLayout(...)
This becomes all too clear if you try to set the background color of the JFrame viamyJFrame.setBackground(Color.green);
and nothing happens. It is for this reason, I'm not too happy with this change. That and also because I must be an old curmudgeon.另外,这里有一个相关的错误:
Also, here's a related bug: