| | |
    Java Beginner Home
    Table of Contents
    Swing Tutorial
     JFrame
     JInternalFrame
     JWindow
     JOptionPane
     JLabel
     JTextField
     JPasswordField
     JTextArea
     JButton
     JRadioButton
     JCheckBox
     JComboBox
     Jlist
     JTabbedPane
     JMenuBar
     Scrollable JPopupMenu
     JToolBar
     BorderLayout
     FlowLayout
     GridLayout
     GridBagLayout
     Java Look and Feel
     Swing Calculator
     Swing Address book
     Shuffle Game
    Download Java Software
    Advertise
    Feedback
    Java books
    Eclipse Plugin Site

Java GridLayout class example



GridLayout

Java Swing Tutorial Explaining the GridLayout. GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

GridLayout Source Code

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

public class GridLayoutDemo {
    public final static boolean RIGHT_TO_LEFT = false;

    public static void addComponentsToPane(Container contentPane) {
        if (RIGHT_TO_LEFT) {
            contentPane.setComponentOrientation(
                ComponentOrientation.RIGHT_TO_LEFT);
        }
//        Any number of rows and 2 columns
        contentPane.setLayout(new GridLayout(0,2));

        contentPane.add(new JLabel("JLabel 1"));
        contentPane.add(new JButton("JButton 2"));
        contentPane.add(new JCheckBox("JCheckBox 3"));
        contentPane.add(new JTextField("Long-Named JTextField 4"));
        contentPane.add(new JButton("JButton 5"));
    }

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame frame = new JFrame("GridLayout Source Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane and components in GridLayout
        addComponentsToPane(frame.getContentPane());

        frame.pack();
        frame.setVisible(true);
    }

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

Output

Download GridLayout Source Code

Java GridLayout Hierarchy

javax.swing
Class GridLayout
java.lang.Object
java.awt.GridLayout
All Implemented Interfaces:
LayoutManager, Serializable

GridLayout Constructor

GridLayout()
Creates a grid layout with a default of one column per component, in a single row.

GridLayout(int rows, int cols)
Creates a grid layout with the spe
cified number of rows and columns.

GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of rows and columns.

 
 
    Java is a trademark of Sun Microsystems, Inc.
| | |
© Copyright 2007-08 javabeginner.com