简体   繁体   中英

Understanding CardLayout and panel visibility

Consider the following:

    JFrame frame = new JFrame();
    frame.setLayout(new CardLayout());

    JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(1000, 1000));
    panel1.setBackground(Color.RED);

    JPanel panel2 = new JPanel();
    panel2.setPreferredSize(new Dimension(100, 100));
    panel2.setBackground(Color.GREEN);

    frame.add(panel1);
    frame.add(panel2);

    frame.pack();
    frame.setVisible(true);

No matter what, the frame ends up being 1000x1000. It's my understanding that using the card layout, only one panel will be shown at a time - hence if that panel is the 100x100, the frame should also be 100x100? But this is not the case. Even when the frame is green (ie it's panel 2 being displayed), the frame is still 1000x1000.

In fact, even adding the line panel1.setVisiblity(false); changes nothing; it still affects the frame size, making it 1000x1000!

I'm clearly misunderstanding how the card layout and frame sizing works. Can someone clear up my confusion?

It's my understanding that using the card layout, only one panel will be shown at a time - hence if that panel is the 100x100, the frame should also be 100x100?

No. A CardLayout will take the preferred size of the widest and tallest components within it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM