Automatically size JPanel inside JFrame

Igor picture Igor · Dec 28, 2008 · Viewed 113k times · Source

I have a JPanel subclass on which I add buttons, labels, tables, etc. To show on screen it I use JFrame:

MainPanel mainPanel = new MainPanel(); //JPanel subclass

JFrame mainFrame = new JFrame();
mainFrame.setTitle("main window title");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setLocation(100, 100);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

But when I size the window, size of panel don't change. How to make size of panel to be the same as the size of window even if it was resized?

Answer

Ole picture Ole · Dec 28, 2008

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.