更改JFrame的默认布局无法正常工作吗?

时间:2019-03-13 13:41:52

标签: java swing jframe layout-manager

我试图将JFrame的默认布局从BorderLayout更改为GridLayout,但是布局没有改变。

下面是我的代码:

import java.awt.GridLayout;
import javax.swing.JFrame;

public class JFrameTest extends JFrame { 
    public JFrameTest() {       
        System.out.println("layout before is " + this.getLayout().toString());
        this.setLayout(new GridLayout(1,2));
        System.out.println("layout after is " + this.getLayout().toString());
    }

    public static void main(String[] args) {
        JFrameTest jft = new JFrameTest();
    }
}

代码的结果是:

layout before is java.awt.BorderLayout[hgap=0,vgap=0]
layout after is java.awt.BorderLayout[hgap=0,vgap=0]

为什么布局未更改为GridLayout

1 个答案:

答案 0 :(得分:2)

您要设置ContentPane的布局,然后检查JFrame的布局。

System.out.println("layout before is " + this.getContentPane().getLayout().toString());
this.getContentPane().setLayout(new GridLayout(1, 2));
System.out.println("layout after is " + this.getContentPane().getLayout().toString());

这将产生您想要的结果。

编辑:OP更改了他的原始代码,使此答案不太正确。 在他的情况下,这将是正确的解决方案:

this.setRootPaneCheckingEnabled(false);
System.out.println("layout before is " + this.getLayout().toString());
this.setLayout(new GridLayout(1, 2));
System.out.println("layout after is " + this.getLayout().toString());