16 April, 2012

GridBag Layout Example

import java.awt.*;
import javax.swing.*;

public class GridBagLayoutTester
{
  final static boolean shouldFill = true;
  final static boolean shouldWeightX = true;
  final static boolean RIGHT_TO_LEFT = false;

  public static void addComponentsToPane(Container pane)
  {
    if (RIGHT_TO_LEFT)
    {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    if (shouldFill)
    {
      gbc.fill = GridBagConstraints.HORIZONTAL;        // natural height, maximum width
    }
    button = new JButton("Button 1");
    if (shouldWeightX)
    {
      gbc.weightx = 0.5;
    }
    gbc.gridx = 0;
    gbc.gridy = 0;
    pane.add(button, gbc);

    button = new JButton("Button 2");
    gbc.gridx = 1;
    gbc.gridy = 0;
    pane.add(button, gbc);

    button = new JButton("Button 3");
    gbc.gridx = 2;
    gbc.gridy = 0;
    pane.add(button, gbc);

    button = new JButton("Long Button 4");
    gbc.ipady = 40;                    // make this component tall
    gbc.weightx = 0.0;
    gbc.gridwidth = 3;
    gbc.gridx = 0;
    gbc.gridy = 1;
    pane.add(button, gbc);

    button = new JButton("5");
    gbc.ipady = 0;                    // reset to default
    gbc.weighty = 1.0;                // request any extra vertical space
    gbc.anchor = GridBagConstraints.PAGE_END;        // bottom of space
    gbc.insets = new Insets(10, 0, 0, 0);        // top padding
    gbc.gridx = 1;                    // aligned with button 2
    gbc.gridwidth = 2;                // 2 columns wide
    gbc.gridy = 2;                    // third row
    pane.add(button, gbc);
  }

  private static void createAndShowGUI()
  {
    JFrame frame = new JFrame("GridBag Layout");    // Create and set up the window.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addComponentsToPane(frame.getContentPane());    // Set up the content pane.
    frame.pack();                    // Display the window.
    frame.setVisible(true);
  }

  public static void main(String[] args)
  {
    javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() {createAndShowGUI();} }  );
  }
}



OUTPUT -:


No comments:

Post a Comment

Thank You !