Set the location of component in a GridBagLayout with Java


To set the location of component, use the GridBagConstraints. Here, we have two components −

GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel("Email-Id − ");
JTextArea text = new JTextArea();
text.setText("Add id here...");

Set the location with gridx and gridy −

gbc.gridx = 0;
gbc.gridy = 0;
layout.setConstraints(label, gbc);
panel.add(label);

The following is an example to set the location of component in a GridBagLayout −

Example

package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      GridBagLayout layout = new GridBagLayout();
      panel.setLayout(layout);
      GridBagConstraints gbc = new GridBagConstraints();
      JLabel label = new JLabel("Email-Id − ");
      JTextArea text = new JTextArea();
      text.setText("Add id here...");
      gbc.gridx = 0;
      gbc.gridy = 0;
      layout.setConstraints(label, gbc);
      panel.add(label);
      gbc.gridx = 1;
      gbc.gridy = 1;
      layout.setConstraints(text, gbc);
      panel.add(text);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements