Emir Emir - 21 days ago 5
Java Question

Starting GridBagLayout from top left corner in Java Swing

I'm new to Java Swing and I have been struggling to start the GridBagLayout from top left corner so that c.gridx=0 c.gridy=0 will put my object on the top left corner.

I'd appreciate if you could help me by telling what I need to do after this point:

JPanel panel = new JPanel(new GridBagLayout());
frame.add(panel);
GridBagConstraints c = new GridBagConstraints();


I know that I have to use NORTHWEST or FIRST_LINE_START constants, but I don't know how. I tried to do it this way' but it did not realize the constants.

frame.getContentPane().add(panel, BorderLayout.NORTHWEST);


Thanks for your help.

Answer

You need to use your GridBagConstraints' anchor property. This should do it for you:

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
frame.add(panel, gbc);

I'm not guaranteeing that you won't have to set other properties of the constraints object to get the layout you desire. In particular, you may need to set widthx and widthy to be 1 so that the panel takes up all of the available space given to it.

Comments