Java Program to create a layout using GridBagLayout

Java 8Object Oriented ProgrammingProgramming

The GridBagLayout creates a grid bag layout manager. It arranges the components in a horizontal and vertical manner.

Here, we have a frame and panel. The panel has two components arranged using GridBagLayout −

JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
JLabel label = new JLabel("Email-Id: ");
JTextArea text = new JTextArea();
text.setText("Add id here...");
panel.setLayout(new GridBagLayout());

Now, set the components to the panel −

panel.add(label);
panel.add(text);

The following is an example to create a layout using GridBagLayout −

Example

package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
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();
      JLabel label = new JLabel("Email-Id: ");
      JTextArea text = new JTextArea();
      text.setText("Add id here...");
      panel.setLayout(new GridBagLayout());
      panel.add(label);
      panel.add(text);
      panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(500, 300);
      frame.setVisible(true);
   }
}

Output


raja
Published on 03-Jun-2019 11:32:09
Advertisements