网格布局






2.50/5 (16投票s)
2003年2月1日

71016

171
一篇介绍如何在Java中使用“Grid”(网格)布局的文章。
引言
本文将演示如何在Java中使用“Grid”布局。网格布局管理器将组件分配到网格的单元格中。网格中的每个单元格大小相同,组件会增长以填充可用区域。这种布局管理器适合于布局看起来像网格的容器;例如,计算器、日历页面或战舰游戏。以下构造函数适用于网格布局
GridLayout(int rows, int cols, int hgap, int vgap)
GridLayout(int rows, int cols)
rows 是网格中的行数,cols 是列数。其中至少一个必须是非零。零表示需要的行数或列数。hgap 是组件之间的水平间隙,默认值为 0 像素。vgap 是组件之间的垂直间隙,默认值也为 0 像素。示例代码
// Imports import java.awt.*; import java.applet.Applet; public class Grid extends Applet{ // Adding Labels Label one = new Label("Team Name"); Label two = new Label("Stadium"); Label three = new Label("Nick Name"); Label four = new Label("Grimsby Town"); Label five = new Label("Blundell Park"); Label six = new Label("Mariners"); Label seven = new Label("Kettering Town"); Label eight = new Label("Rockignham Road"); Label nine = new Label("Poppies"); Label ten = new Label("Boston United"); Label eleven= new Label("York Street"); Label twelve= new Label("Pilgrims"); //The Grid Layout uses the simplest form of the add method which requires only a reference to a component. public void init(){ setLayout(new GridLayout(4,3)); add(one); one.setBackground(Color.red); add(two); two.setBackground(Color.red); add(three); three.setBackground(Color.red); add(four); four.setBackground(Color.green); add(five); five.setBackground(Color.green); add(six); six.setBackground(Color.green); add(seven); seven.setBackground(Color.blue); add(eight); eight.setBackground(Color.blue); add(nine); nine.setBackground(Color.blue); add(ten); ten.setBackground(Color.orange); add(eleven); eleven.setBackground(Color.orange); add(twelve); twelve.setBackground(Color.orange); } }