So what I am trying to do is create this:
I am using a gridbag layout and here is what I have so far:
public class board {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JPanel leftTop = new JPanel();
leftTop.setPreferredSize(new Dimension(251,300));
leftTop.setBackground(Color.black);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(leftTop, c);
JPanel middleTop = new JPanel();
middleTop.setPreferredSize(new Dimension(251,200));
middleTop.setBackground(Color.green);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
pane.add(middleTop, c);
JPanel rightTop = new JPanel();
rightTop.setPreferredSize(new Dimension(251,600));
rightTop.setBackground(Color.blue);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 0;
pane.add(rightTop, c);
JPanel leftBottom = new JPanel();
leftBottom.setPreferredSize(new Dimension(251,300));
leftBottom.setBackground(Color.red);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
pane.add(leftBottom, c);
JPanel middleBottom = new JPanel();
middleBottom.setPreferredSize(new Dimension(251,400));
middleBottom.setBackground(Color.yellow);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
pane.add(middleBottom, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
It creates something like:
How would I push up the panels so they are touching each other like in my first picture. I looked through the GridBagConstraints but I could not find anything that looked like it would work. Thanks!
Instead of trying to solve the complete layout problem with one layout manager, it's often simpler to nest layouts. For example, your example code could be modified to use a horizontal grid layout (to keep the columns equal width - I don't actually know if you want to force that. If not, then
FlowLayout
orBoxLayout
would be better), and the columns use aBoxLayout
each:Results in:
(I modified the preferred sizes a bit to make the image smaller. As a further note it's usually better to override getPreferredSize() rather than use setPreferredSize(); setPreferredSize() is convenient for the quick example though)