如此处所述:Adding Components to the Content Pane ,
The default content pane is a simple intermediate container that inherits from JComponent, and that uses a BorderLayout as its layout manager.
这是一个证明:
JFrame frame = new JFrame();
LayoutManager m = frame.getContentPane().getLayout();
System.out.println(m instanceof BorderLayout); // prints true
但是,你能解释一下下面代码的输出吗?
JFrame frame = new JFrame();
LayoutManager m = frame.getContentPane().getLayout();
System.out.println(m);
System.out.println(m.getClass().getName());
LayoutManager m2 = new BorderLayout();
System.out.println(m2);
System.out.println(m2.getClass().getName());
输出:
javax.swing.JRootPane$1[hgap=0,vgap=0]
javax.swing.JRootPane$1
java.awt.BorderLayout[hgap=0,vgap=0]
java.awt.BorderLayout
最佳答案
这解释了你的结果:
protected Container createContentPane() {
JComponent c = new JPanel();
c.setName(this.getName()+".contentPane");
c.setLayout(new BorderLayout() {
/* This BorderLayout subclass maps a null constraint to CENTER.
* Although the reference BorderLayout also does this, some VMs
* throw an IllegalArgumentException.
*/
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints == null) {
constraints = BorderLayout.CENTER;
}
super.addLayoutComponent(comp, constraints);
}
});
return c;
}
创建内容 Pane 的方法创建了一个继承自 BorderLayout 的匿名内部类。 因此,对 instanceof 进行测试将返回 true 但它是另一个类,因此类名不同。
关于java - JFrame 的 contentPane 的 LayoutManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11389387/