-3

I am trying to add button in my GUI using Gridbagconstraints in LayoutManager in Java. The location of the button is always in the center, irrespective of the coordinates.

package StudentInfo;
import javax.swing.*;
import java.awt.*;

public class Gui {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    frame.add(panel);
    panel.setLayout(new GridBagLayout());
    frame.setSize(600,600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);

    GridBagConstraints gbc = new GridBagConstraints();

    JButton b = new JButton("Hello");
    gbc.gridx=1;
    gbc.gridy=1;
    panel.add(b,gbc);

    JButton v = new JButton("exit");
    gbc.gridx=1;
    gbc.gridx=0;
    panel.add(v,gbc);

}
}

Output

enter image description here

Question

How to define co-ordinates of the buttons and place them at desired location?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Dhaval
  • 5
  • 3
  • 2
    Your question is missing an important detail: where do you **want** to place those buttons. One (very poor) solution is to use a null layout and absolute positioning, but this will result in a GUI that only works well on one platform and that is very difficult to debug, maintain and enhance, and so should be avoided. The ***much*** better solution is to better define your requirements and then use the Swing layout managers appropriately to best position your components. So again, please help us -- what is your desired GUI? Please show an image. – Hovercraft Full Of Eels Jul 26 '17 at 21:32
  • In addition to the advice of @HovercraftFullOfEels: Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, **and if resizable, with more width and height.** – Andrew Thompson Jul 27 '17 at 08:49
  • @HovercraftFullOfEels The GUI I want is 2 textfields and two buttons. the two text field one below the other and the button side by side below the second textfield – Dhaval Jul 27 '17 at 12:47

1 Answers1

2

You need to set weightx and weighty for the GridBagConstraints object.

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container. How to Use GridBagLayout

I recommend you read through this tutorial as well as the ones on the other swing layout managers if you want to continue working with GUIs in Java as they require a good deal of proficiency to use properly.

Matt
  • 113
  • 7