JAVA:填充框架的方法。 add(),setContentPane(),getContentPane()

我找到了三种方法来填充我的JFrame框架= new JFrame(“…”)createContentPanel返回一个JPanel,createToolBar返回一个ToolBar。

frame.add(this.createToolBar(), BorderLayout.PAGE_START); //this works and puts the ToolBar above and the ContentPanel under it
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(…)来填充我的框架。

你是对的,你使用哪个( JFrame#add(...)JFrame#getContentPane().add(...) )并不重要,因为它们基本上都调用相同的代码,但是有时会在将来当你需要访问contentPane本身时,例如你想要改变它的边框,设置它的背景颜色或确定它的尺寸,所以你可能会在某些时候使用getContentPane(),从而获得了解它并熟悉它会很有帮助。

//这只会将最后一个放入JFrame

您需要了解布局管理器的工作方式。 默认内容窗格是使用BorderLayout的JPanel。 添加组件但未指定约束时,它默认为CENTER。 但是,您只能在中心有一个组件,因此布局管理器只知道添加的最后一个组件。 调用布局管理器时,它会设置该组件的size()和location()。 另一个组件的大小为0,因此从不绘制。

在Java 1.6中,您可以使用JFrame的add方法: http : //download.oracle.com/javase/6/docs/api/javax/swing/JFrame.html (它将被委托给contentPane。)

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html

哪个说:

JFrame类与Frame略有不兼容。 与所有其他JFC / Swing顶级容器一样,JFrame包含一个JRootPane作为其唯一的子级。 根窗格提供的内容窗格通常应包含JFrame显示的所有非菜单组件。 这与AWT Frame案例不同。 例如,要将子项添加到AWT框架,您需要编写:

  frame.add(child); 

但是,使用JFrame需要将子项添加到JFrame的内容窗格中:

  frame.getContentPane().add(child); 

设置布局管理器,删除组件,列出子项等也是如此。 通常应将所有这些方法发送到内容窗格而不是JFrame本身。 内容窗格始终为非null。 尝试将其设置为null将导致JFrame抛出exception。 默认内容窗格将在其上设置BorderLayout管理器。