Im using GridBagLayout for placing the panels as below. I want to align everything to the top. I can manage this by using BorderLayout.NORTH on my background-panel (jp) but then the backgroundpanel doesnt fill the window
How can I align my panels to the top by using GridBagLayout?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
JPanel jp = new JPanel();
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JPanel jp3 = new JPanel();
JPanel jp4 = new JPanel();
public Test() {
jp1.setPreferredSize(new Dimension(100, 100));
jp2.setPreferredSize(new Dimension(100, 100));
jp3.setPreferredSize(new Dimension(100, 100));
jp4.setPreferredSize(new Dimension(100, 100));
jp1.setBackground(Color.red);
jp2.setBackground(Color.blue);
jp3.setBackground(Color.yellow);
jp4.setBackground(Color.green);
GridBagLayout g = new GridBagLayout();
jp.setLayout(g);
jp.setBackground(Color.BLACK);
GridBagConstraints con;
con = new GridBagConstraints();
con.insets = new Insets(3, 3, 3, 3); // top, left, bottom, right
// PANEL ONE
con.gridx = 0;
con.gridy = 0;
g.setConstraints(jp1, con);
jp.add(jp1);
// PANEL TWO
con.gridx = 1;
con.gridy = 0;
g.setConstraints(jp2, con);
jp.add(jp2);
// PANEL THREE
con.gridx = 0;
con.gridy = 1;
g.setConstraints(jp3, con);
jp.add(jp3);
// PANEL FOUR
con.gridx = 1;
con.gridy = 1;
g.setConstraints(jp4, con);
jp.add(jp4);
this.setSize(600, 300);
// I CAN MANAGE TO GET THE PANELS ALIGNED TO THE TOP BY USING BORDERLAYOUT
// LIKE BELOW BUT THEN THE BACKGROUNDPANEL DOESNT FILL THE WINDOW
// this.add(jp, BorderLayout.NORTH);
this.add(jp);
}
public static void main(String[] args) {
new Test().setVisible(true);
}
}
but then the backgroundpanel doesnt fill the window
Why do you want the backgroundPanel to fill the window?
If you just want a black background then you can do:
//this.add(jp);
this.getContentPane().setBackground( jp.getBackground() );
this.add(jp, BorderLayout.NORTH);
Or when using the GridBagLayout you need to specify the "anchor" and "weighty" contraints:
con.gridx = 0;
con.gridy = 0;
con.anchor = ...;
...
con.gridx = 1;
con.gridy = 1;
con.weighty = ...;
Read the section from the Swing tutorial on How to Use GridBagLayout to understand what these constraints do. I've indicated which contraints you need to use and where to included them in your example.
Another approach is to use a wrapper panel:
JPanel wrapper = new JPanel();
wrapper.setBackground( Color.BLACK );
wrapper.add( jp );
this.add( wrapper );
By default a JPanel uses a FlowLayout which will respect the size of any component added to the panel.