Change Panel size on button click

后端 未结 3 1517
盖世英雄少女心
盖世英雄少女心 2020-12-19 11:08

I have the following code:

package in.res.num.tapb.ui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.         


        
3条回答
  •  伪装坚强ぢ
    2020-12-19 11:27

    You should never use setSize() when using a layout manager. It is the job of the layout manager to determine the size. You can provide hints to the layout manager by setting the peferred or minimum or maximum sizes. However it is not recommend that you do this since components and panels should be displayed at their preferred size which will be determined by the layout manager you are using. If you did override the size then the code should be:

    // enrol.setSize(new Dimension(400, 200));
    enrol.setPreferredSize(new Dimension(400, 200));
    

    However, this still won't work the way you want because the job of the CardLayout is to determine the largest size of all panels added to the panel using a CardLayout. So when you swap from panel to panel you don't get the size of each individual panel. This is s better experience for the user because the user doesn't want to see the frame size keep changing every time they hit a button.

    If you did want to have the frame change size every time you click on a button then the basic code would be:

    mainPanel.remove(oldPanel);
    mainPanel.add(newPanel);
    frame.pack();
    

    Then the layout manager of the main panel will observe the preferred size of the newlay added panel.

提交回复
热议问题