Search code examples
javaswinglayoutgridbaglayout

how to set Constraints to GridBagLayout


I am looking for a way to add jlabel and jtextfield on first line and 2 jbuttons on second line and in the centre of the jpanel. but how to set the constraints using gridbaglayout?

    selectionPanel.add(new JLabel("Department Name"));
    selectionPanel.add(new JTextField(deptName));
    selectionPanel.add(addBut);
    selectionPanel.add(deleteBut);

Solution

  • First you'll need to set layout to GridBagLayout.

    Then you'll need to create new GridBagConstraints for each component (this way, you'll not get values from the last component on the next you're creating).

    In the add() method, you'll pass the component and constraints.

    setLayout(new java.awt.GridBagLayout())
    java.awt.GridBagConstraints constraints = new java.awt.GridBagConstraints();
    constraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
    constraints.weighty = 0.1;
    constraints.weightx = 0.3;
    javax.swing.JButton unlockButton = new javax.swing.JButton("jbutton text");
    add(unlockButton, constraints);