the program below is to position a jpanel at the top left conner of jframe with gridbaglayout but instead a very small box is displayed in center of jframe. when I set the layout of jframe to null, the jpanel displays fine. can someone tell me why the jpanel is compressed to the center of frame with gridbaglayout? i really need to use gridbag. please help
import java.awt.*;
import javax.swing.*; //swing package
public class Major {
//defining the constructor
public Major() {
JFrame maFrame = new JFrame("The main screen"); //creating main Jframe
JPanel headPanel = new JPanel(); //creating the header panel
maFrame.setSize(900, 700); //setting size
maFrame.setBackground(Color.LIGHT_GRAY); //setting color of frame
Container container = maFrame.getContentPane();
container.setLayout(new GridBagLayout()); //setting layout of main frame
GridBagConstraints cns = new GridBagConstraints(); //creating constraint
cns.gridx = 0;
cns.gridy = 0;
maFrame.setLocationRelativeTo(null); //centering frame
headPanel.setBackground(Color.WHITE);
headPanel.setSize(200, 150);
container.add(headPanel, cns);
maFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
maFrame.setVisible(true); //making the frame visible
}
//defining the main method
public static void main(String[] args) {
new Major(); //instantiating the class
}
}
You must set the
weightx
andweighty
of at least one GridBagConstraint to some value greater than 0.0!The weight attributes are are used to indicate what happens with extra space if the whole layout is smaller than the available space. If all weights (for one direction) are zero, the default value, the whole layout is centered. If at least one weight is greater than zero, the extra space is distributed to the columns or rows in proportion to its weight, so the layout will occupy all available space.
Seems like you forgot to provide,
weightx
andweighty
constraints to yourGridBagConstraints
, As you provide them, you will see your JPanel.Here I had modified your code with those Constraints.
And never use this line,
headPanel.setSize(200, 150);
, as I had commented it out, since the constraints I had mentioned will sort this out for you.Adding a new Code with image :
here is the output :