Xenophrontistes
Xenophrontistes

Reputation: 3

Adding Multiple Panels with Different Sizes in One Frame

I am trying to add more panels to my frame, but the program seems to ignore all the other panels than the first one I added. How should I add the panels?

I have checked other people's questions and their answers, but none of them seemed to be the solution to mine.

frame = new JFrame("Hey");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mid = new JPanel(new GridLayout(7,7));
JPanel top = new JPanel();

frame.add(top);
frame.add(mid);
frame.pack();
frame.setVisible(true);

The program ignores the "top" panel, along with the buttons I added to it.

Upvotes: 0

Views: 464

Answers (1)

gla3dr
gla3dr

Reputation: 2309

From the JFrame documentation:

The default content pane will have a BorderLayout manager set on it.

So you should use the BorderLayout regions in order to add your JPanels to the JFrame's content pane like this:

frame.add(top, BorderLayout.NORTH);
frame.add(mid, BorderLayout.CENTER);

Otherwise, the BorderLayout will default to adding everything to the CENTER region:

As a convenience, BorderLayout interprets the absence of a string specification the same as the constant CENTER:

Panel p2 = new Panel();
p2.setLayout(new BorderLayout());
p2.add(new TextArea());  // Same as p.add(new TextArea(), BorderLayout.CENTER);

and you will only see the JPanel added last because:

Each region may contain no more than one component

Upvotes: 0

Related Questions