JAVA: Ways to fill a Frame. add(), setContentPane(), getContentPane()(JAVA:填充框架的方法.添加(),setContentPane(),getContentPane())
问题描述
我找到了三种方法来填充我的 JFrame frame = new JFrame("...")createContentPanel 返回一个 JPanel,createToolBar 返回一个 ToolBar.
I found three ways to fill my JFrame frame = new JFrame("...") createContentPanel returns a JPanel and createToolBar returns a ToolBar.
frame.add(this.createToolBar(), BorderLayout.PAGE_START); //this works and puts the ToolBar above and the ContentPanel under it<br>
frame.add(this.createContentPanel(), BorderLayout.CENTER);
frame.setContentPane(this.createContentPanel()); //this lets the JToolBar hover over the ContentPanel
frame.getContentPane().add(this.createToolBar());
frame.getContentPane().add(this.createContentPanel()); //this only puts the last one into the JFrame
frame.getContentPane().add(this.createToolBar());
现在我想知道为什么我应该使用 getContentPane()/setContentPane() 方法,如果我可以使用一个简单的 frame.add(...) 来填充我的框架.
And now I am wondering why should i use the getContentPane()/setContentPane() method if i could just use a simple frame.add(...) to fill my frame.
推荐答案
你是对的,你使用哪个并不重要(JFrame#add(...) vs. JFrame#getContentPane().add(...)) 因为它们本质上都调用相同的代码,但是将来有时您需要访问 contentPane 本身,例如,如果您想要更改其边框、设置其背景颜色或确定其尺寸,因此您可能会在某些时候使用 getContentPane(),因此了解并熟悉它会很有帮助.
You are right that it doesn't matter which you use (JFrame#add(...) vs. JFrame#getContentPane().add(...)) since they both essentially call the same code, however there will be times in the future when you'll need access to the contentPane itself, such as if you want to change its border, set its background color or determine its dimensions, and so you'll likely use getContentPane() at some point, and thus getting to know it and be familiar with it would be helpful.
这篇关于JAVA:填充框架的方法.添加(),setContentPane(),getContentPane()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JAVA:填充框架的方法.添加(),setContentPane(),getContentPane()
基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
