Search code examples
javaswinguser-interfaceframe

java GUI set cardlayout frame size


So I am trying to learn how to use card layout and in this sample code I would like to change the size of the frame to a certain size but using setSize does not work.

the following also does not work in the when added to createAndShowGui() function

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

frame.setPreferredSize(new Dimension(500,200));

import java.awt.CardLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class MainGui2 extends JPanel {
    private CardLayout cardLayout = new CardLayout();
    private WelcomePanel welcomePanel = new WelcomePanel(this);
    private HomePanel homePanel = new HomePanel();

    public MainGui2() {
        setLayout(cardLayout);
        add(welcomePanel, WelcomePanel.NAME);
        add(homePanel, HomePanel.NAME);
    }

    public void showCard(String name) {
        cardLayout.show(this, name);
    }

    private static void createAndShowGui() {
        MainGui2 mainPanel = new MainGui2();

        JFrame frame = new JFrame("MainGui2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        //frame.pack();
        frame.setSize(550, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }

}

class WelcomePanel extends JPanel {
    public static final String NAME = "welcome panel";
    private MainGui2 mainGui2;

    public WelcomePanel(final MainGui2 mainGui2) {
        this.mainGui2 = mainGui2;
        add(new JLabel(NAME));
        add(new JButton(new AbstractAction("Logon") {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainGui2.showCard(HomePanel.NAME);
            }
        }));
    }
}

class HomePanel extends JPanel {
    public static final String NAME = "home panel";

    public HomePanel() {
        add(new JLabel(NAME));
    }
}

Solution

  • I would like to change the size of the frame to a certain size

    Don't try to hard code frame sizes.

    If you want extra space around the panels then in the constructor of your MainGui2 class you can add:

    setBorder( new EmptyBorder(50, 50, 50, 50) );
    

    This will adjust the preferred size of the panel and this size will now be taken into account when the pack() method is used.