So I have 6 panels, all of them used a grid layout. And I put them together using gridbaglayout, here is the design I wanted
As you wrote c.gridx = 0 and c.gridy = 0
, you forgot to specify how many columns you want this JPanel
to occupy. In order to specify that, you should be using c.gridwidth = 2
, which tells the layout that this JPanel
needs space for two columns.
To get an output like this:
Here is a small working example:
import java.awt.*;
import javax.swing.*;
// http://stackoverflow.com/questions/10968853/two-jpanels-in-jframe-one-under-other
public class GridBagLayoutExample
{
// http://stackoverflow.com/questions/10977017/grid-bag-layout-not-displaying-the-way-i-want
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 0.5;
gbc.weighty = 0.2;
JPanel topLeftPanel = new JPanel();
topLeftPanel.setOpaque(true);
topLeftPanel.setBackground(Color.DARK_GRAY);
contentPane.add(topLeftPanel, gbc);
gbc.gridx = 2;
JPanel topRightPanel = new JPanel();
topRightPanel.setOpaque(true);
topRightPanel.setBackground(Color.BLUE);
contentPane.add(topRightPanel, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.25;
gbc.weighty = 0.8;
JPanel firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.RED);
contentPane.add(firstPanel, gbc);
gbc.gridx = 1;
JPanel secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.GREEN.darker());
contentPane.add(secondPanel, gbc);
gbc.gridx = 2;
JPanel thirdPanel = new JPanel();
thirdPanel.setOpaque(true);
thirdPanel.setBackground(Color.WHITE);
contentPane.add(thirdPanel, gbc);
gbc.gridx = 3;
JPanel fourthPanel = new JPanel();
fourthPanel.setOpaque(true);
fourthPanel.setBackground(Color.MAGENTA);
contentPane.add(fourthPanel, gbc);
frame.setContentPane(contentPane);
frame.setSize(200, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutExample().displayGUI();
}
});
}
}