JFrame getLayout method does not return set cardLa

2019-08-07 03:48发布

问题:

I am setting a CardLayout as the a JFrame's layout but when I call the getLayout method a border layout is returned.

import java.awt.CardLayout;

import javax.swing.JFrame;

public class SSCCE {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        CardLayout cl = new CardLayout();
        frame.setLayout(cl);
        System.out.println(cl);
        System.out.println(frame.getLayout());

    }
}

This is printed to console:

java.awt.CardLayout[hgap=0,vgap=0]
java.awt.BorderLayout[hgap=0,vgap=0]

回答1:

JFrame redirects the setLayout() to content pane. That's source snippet

public void setLayout(LayoutManager manager) {
    if(isRootPaneCheckingEnabled()) {
        getContentPane().setLayout(manager);
    }
    else {
        super.setLayout(manager);
    }
}