更改JFrame的默认布局不起作用?

问题描述 投票:0回答:1

我试图将JFrameBorderLayout的默认布局更改为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

java swing jframe layout-manager
1个回答
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());
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.