How to remove extra spaces in JFrame using GridBagLayout?

590 views Asked by At

When I insert any button or any component in my frame and set the component gridx and gridy to values 0, it does not put that component at the starting of the frame instead it put the component somewhere in the center.

How to remove the spaces and put my component at the very starting of the frame?

Following is the code:

         JFrame frame = new JFrame("Grigbag layout");

         JPanel pane = new JPanel(new GridBagLayout());

         GridBagConstraints c = new GridBagConstraints();

         JButton button = new JButton("First button");

         c.gridx = 0;
         c.gridy = 0;
         pane.add(button, c);

enter image description here

3

There are 3 answers

0
Masud Parves Bhuiyan On

frame is using the default layout. Set frame's layout with something like

frame.setLayout(new FlowLayout(FlowLayout.LEFT));
0
Programmer On

I suggest you to use Flow Layout and also add this code

frame.pack();

as mentioned by Andrew Thompson above

for more : https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html

0
A.K. On

Use the frame.pack()method and remove the frame.setSize(); method.