Java Swing Tutorials - Herong's Tutorial Examples - Version 4.11, by Dr. Herong Yang
java.awt.GridLayout - Grid Layout
This section provides a tutorial example on how to create a GridLayout to layout components in a container. GridLayout can have many elements arranged in predefined rows and columns.
java.awt.GridLayout - A layout that:
Again, I wrote another program to try to display my window with GridLayout:
/* GridLayoutTest2.java * Copyright (c) 2014, HerongYang.com, All Rights Reserved. */ import java.awt.*; import javax.swing.*; public class GridLayoutTest2 { public static void main(String[] a) { JFrame myFrame = new JFrame("GridLayout Test"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container myPane = myFrame.getContentPane(); myPane.setLayout(new GridLayout(2,1)); myPane.add(getFieldPanel()); myPane.add(getButtonPanel()); myFrame.pack(); myFrame.setVisible(true); } private static JPanel getFieldPanel() { JPanel p = new JPanel(new GridLayout(4,2)); p.setBorder(BorderFactory.createTitledBorder("Details")); p.add(new JLabel("Name:",SwingConstants.RIGHT)); p.add(new JTextField(16)); p.add(new JLabel("System:",SwingConstants.RIGHT)); p.add(getSystemPanel()); p.add(new JLabel("Language:",SwingConstants.RIGHT)); p.add(getLanguagePanel()); p.add(new JLabel("Year:",SwingConstants.RIGHT)); p.add(new JComboBox<String>( new String[] {"2021","2022","2023"})); return p; } private static JPanel getButtonPanel() { JPanel p = new JPanel(new GridLayout(1,2)); p.add(new JButton("OK")); p.add(new JButton("Cancel")); return p; } private static JPanel getSystemPanel() { JRadioButton unixButton = new JRadioButton("Unix",true); JRadioButton winButton = new JRadioButton("Window",false); ButtonGroup systemGroup = new ButtonGroup(); systemGroup.add(unixButton); systemGroup.add(winButton); JPanel p = new JPanel(new GridLayout(1,2)); p.add(unixButton); p.add(winButton); return p; } private static JPanel getLanguagePanel() { JPanel p = new JPanel(new GridLayout(1,3)); p.add(new JCheckBox("Java",true)); p.add(new JCheckBox("C++",true)); p.add(new JCheckBox("Perl",false)); return p; } }
Run it. What do you think about the result? You don't like it, right?
All components are aligned correctly in both directions now. But all components are having wrong sizes.
So, GridLayout is still not good for my example.
Sample programs listed in this section have been tested with JDK 1.7.0 to 1.8.0.
Last update: 2014.
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
JRadioButton - Swing Radio Button Class
JTextField - Swing Text Field Class
Menu Bar, Menus, Menu Items and Listeners
Creating Internal Frames inside the Main Frame
►Layout of Components in a Container
java.awt.BorderLayout - Border Layout
java.awt.FlowLayout - Flow Layout
java.awt.BoxLayout - Box Layout
►java.awt.GridLayout - Grid Layout
java.awt.GridBagLayout - Grid Bag Layout
JEditorPane - The Editor Pane Class