import java.awt.
*;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame {
public GridBagLayoutExample() {
setTitle("GridBag Layout Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a panel to hold the buttons
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Add buttons to the panel
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JButton("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(new JButton("Button Two"), gbc);
gbc.gridx = 2;
gbc.gridy = 0;
panel.add(new JButton("Button Three"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
panel.add(new JButton("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 3;
panel.add(new JButton("Button Five"), gbc);
// Add the panel to the frame
add(panel);
pack();
setLocationRelativeTo(null);
setVisible(true);
public static void main(String[] args) {
new GridBagLayoutExample();
OUTPUT:
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBag Layout in Java Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Label for "Name"
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
panel.add(new JLabel("Name:"), gbc);
// Text field for "Name"
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JTextField(20), gbc);
// Label for "Comments"
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
panel.add(new JLabel("Comments:"), gbc);
// Text area for "Comments"
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
panel.add(new JTextArea(5, 20), gbc);
// Submit button
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
panel.add(new JButton("Submit"), gbc);
frame.add(panel);
frame.pack();
frame.setVisible(true);