Skip to content
Advertisement

How do I put two Jpanels/Jbuttons in the borderlayout north section?

How do I display two JPanels in the ‘North’ in borderlayout?

Here’s and example code that outputs a GUI with three distinct rows, Top, Middle, Bottom. There’s one button covering the first row, 3 buttons covering the second row, and one covering the bottom row.

JavaScript

Output of above code: output of above code

However, I’d like there to be two jpanels in the North section so it’d make 4 “rows” like this:

JavaScript

I’ve tried simply just adding it as follows:

JavaScript

But what happens here is the second button just replaces the first one:

JavaScript

How would I get two rows in the north layout area?

Advertisement

Answer

Creating a more complex GUI is straightforward when you think of a GUI as a JFrame with as many JPanels as necessary to define the GUI.

Here’s the GUI you were looking for.

Button GUI

I created a JPanel for each section of the JFrame (NORTH, CENTER, and SOUTH). Each of those JPanels used a BorderLayout so that when you expand the GUI, the NORTH and SOUTH buttons stay the same height.

Here’s the complete runnable example code.

JavaScript
Advertisement