0

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?

1
  • 6
    1) Don't use a null layout. Swing was designed to be used with layout managers 2) Your top level panel can use a CardLayout. All panels will be sized to the size of the largest panel added. See the Swing tutorial o How to Use CardLayout for more information and working examples. Keep a link to the tutorial handy for all Swing basics. Commented May 22, 2022 at 19:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.