Home > OS >  JFrame and JPanel sizing
JFrame and JPanel sizing

Time:05-23

I have a JFrame and a few JPanels that are displayed depending on where the user goes (to login, homepage etc), is there a way to set all JPanels to the same size without having to manually specify?

public mainApp() {
    main = new JFrame("Application");
    main.setSize(640, 480);
    main.setVisible(true);
}

private JPanel loginScreen() {
    login = new JPanel(null);
    login.setSize(640, 480);
    login.setVisible(true);
    
}

For example I have 5 different JPanels, and have to specify the size in each, is there a way to set a default size that is the same as the JFrame?

CodePudding user response:

You have different valid options here. Knowing that you want to change from one view to another and keep the same size, it sounds like the best option would be to use a CardLayout allowing you to change between the different views without having to worry about repainting and revalidating stuff (this tutorial from Oracle helped me a lot back when I was learning to use this layout: Oracle - How to use CardLayout.

However, as usual with Swing/AWT this is not the only valid option. For example, you could also use the BorderLayout that is applied by default to the ContentPane from the JFrame and add the desired JPanel to the Center of that BorderLayout. However, you would have to manage the view-changing process in this case.

  • Related