java – JFrame的contentPane的LayoutManager
作者:互联网
如上所述: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());
OUTPUT:
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;
}
创建contentpane的方法创建了一个继承自BorderLayout的匿名内部类.
因此,对instanceof的测试将返回true,但是它的另一个类因此类名称不同.
标签:java,swing,jframe,border-layout,contentpane 来源: https://codeday.me/bug/20190620/1248952.html