我正在阅读 Head First Java。在介绍 GUI 时(对于那些拥有本书的人,第 354 页),作者写道:
frame.getContentPane().add(button);
"You don't add things to the frame directly. Think of the frame as the trim around the window, and you add things to the window pane."
看了Java API entry for JFrame之后, 我看到 JFrame 是 Component 的子类并且继承了 Component 的 add(Component) ,所以它可以简单地写:
frame.add(button);
为什么书上推荐使用frame.getContentPane.add(button)?
提前致谢!
最佳答案
您可以在 JFrame 上调用 add(...)
,但实际上它所做的是调用 getContentPane().add(... )
根据 JFrame API,也称为“语法糖”。但请注意,在执行此操作时,您实际上并不是将其直接添加到 JFrame,而是将其添加到 contentPane。这很重要,因为 JFrame 由组件组成,如 JFrame/top level window Swing Tutorial很好的解释。
我自己,我更喜欢文字 getContentPane().add(...)
因为不是所有的 JFrame 行为都会以这种方式工作,例如 setBackground(...)
,所以字面意思让我想起了我在做什么。
关于java - 为什么我不能在 JFrame 上调用 add() 而必须在容器上调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777126/