Home
01 Getting Started
02 Concepts
03 Variables & Data Types
04 Control Logic
05 Modifiers
06 GUI
07 Other Useful Classes
08 Handling Events
09 Handling Exceptions
10 Project 01 - Mortg Calc
11 More On Applets
12 Layout Manager
a Absolute Positioning
b Flow Layout
c Border Layout
d Grid Layout
e Grid Bag Layout
f Mixing Layout Managers
13 Project 02 - Calculator
14 Threads
15 Project 03 - Wake Up
16 File I/O
17 Project 04 - File I/O
Expanded Table of Contents
Debugging Hints
HTML Review
Download Samples
|
Previous Next
Grid Layout
With the GridLayout you specify the number of rows and columns. Then the components are added from left to right. When the row becomes full, the next row is started.
After testing the code below, be sure to increase and decrease the size of the window. In this case, you will see the sizes changing for the components instead of the positions, as you saw with the FlowLayout.
The format of the constructor is (last 2 parameters are optional).
GridLayout(int rows, int cols, int horizontal_gap, int vertical_gap)
Test modifying the parameter list from
GridLayout nature = new GridLayout(3, 3, 10, 10);
GridLayout nature = new GridLayout(3, 3);
Notice the spacing changes between each button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnimalGrid extends JFrame {
JButton dog = new JButton("Dog");
JButton cat = new JButton("Cat");
JButton bird = new JButton("Bird");
JButton pig = new JButton("Pig");
JButton mouse = new JButton("Mouse");
JButton lion = new JButton("Lion");
JButton tiger = new JButton("Tiger");
JButton bear = new JButton("Bear");
JButton deer = new JButton("Deer");
public AnimalGrid() {
super("Animal GridLayout");
setSize(260, 260);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
GridLayout nature = new GridLayout(3, 3, 10, 10);
pane.setLayout(nature);
pane.add(dog);
pane.add(cat);
pane.add(bird);
pane.add(pig);
pane.add(mouse);
pane.add(lion);
pane.add(tiger);
pane.add(bear);
pane.add(deer);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
AnimalGrid frame = new AnimalGrid();
}
}
Previous Next
|
|