bighash1
bighash1

Reputation: 11

Changing the default layout for JFrame not working?

I was trying to change the default layout of the the JFrame from BorderLayout to GridLayout but the layout does not change.

Below is my code:

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();
    }
}

The result of the code is:

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

Why is the layout not changing to GridLayout?

Upvotes: 0

Views: 377

Answers (1)

jalako
jalako

Reputation: 146

You are setting the Layout of the ContentPane and then checking the layout of the 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());

This produces your desired result.

EDIT: The OP changed his original code making this answer not quite right. In his case this would be the proper solution:

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());

Upvotes: 2

Related Questions