Mapet
Mapet

Reputation: 115

GridBagLayout allignement

Iam trying to find out how GridBagLayout works,because i have had never used it. I will post source code and picture of that gui. i have problem with components to allign. i want to put button to be in the middle of two components(on one side checkboxgroup and on the other is JTextArea. and i managed but it is alligned in the bottom and i want to allign it to be in the middle of the height of both components.

public class GUI extends JFrame {
public GUI(){
    setSize(600,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setTitle("ridBagLayout[![enter image description here][1]][1]");
    JPanel panel=new JPanel(new GridBagLayout());
    GridBagConstraints c=new GridBagConstraints();
    String[]niz={"C Sharp","Java","PHP","VisualBasic"};
    c.anchor=GridBagConstraints.PAGE_START;
    c.weighty=1.0;
    c.gridx=0;
    c.gridy=0;

     c.insets=new Insets(30,30,0,0);
    panel.add(new JComboBox(niz),c);
    c.gridx=1;
    //c.insets=new Insets(10,0,0,0);

    panel.add(new JButton("Get drop down item"),c);
    c.gridx=2;
    c.ipadx=20;
    panel.add(new JTextField(15),c);
    JCheckBox visualBasic=new JCheckBox("Visual Basic");
JCheckBox cSharp=new JCheckBox("C Sharp");
JCheckBox java=new JCheckBox("Java");
JCheckBox php=new JCheckBox("PHP");

     JPanel checkbox=new JPanel();
     checkbox.setLayout(new GridLayout(4,0,5,5));
checkbox.add(visualBasic);
checkbox.add(cSharp);
checkbox.add(java);
checkbox.add(php);
 javax.swing.border.Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
checkbox.setBorder(raisedetched);
    c.insets=new Insets(0,20,0,0);
    c.gridx=0;
    c.gridy=1;
    panel.add(checkbox,c);

    c.gridx=1;

    c.ipadx=30;
   c.anchor=GridBagConstraints.CENTER;
    panel.add(new JButton("Selected Item"),c);

    c.gridx=2;
    c.gridy=1;
    c.ipadx=20;
    c.anchor=GridBagConstraints.NORTH;
    panel.add(new JTextArea(7,15),c);

    add(panel);
    setVisible(true);
}

}

enter image description here

Upvotes: 0

Views: 56

Answers (1)

Joe Hackerberg
Joe Hackerberg

Reputation: 467

GridBagLayout is one of the most powerful layouts to use in Java, but it requires some nesting in order to obtain a good result.

In your case, maybe you need to put that button inside a panel and set its alignments properties to CENTER.

There is lot of documentation about GridBagLayout but another way to see how it works could be to create a new project in an IDE like NetBeans and create that GUI through its graphical editor and see the generated code.

Upvotes: 2

Related Questions