//GridLayoutDemo网格布局管理器练习 import java.awt.*; import java.awt.event.*; @SuppressWarnings("serial") public class GridLayoutDemo extends Frame { private final String names[] = { "1", "2", "3", "4", "5", "6" }; private Button[] buttons = new Button[6]; private boolean flag = true; final GridLayout layout1 = new GridLayout(2, 3, 5, 10); final GridLayout layout2 = new GridLayout(3, 2); public GridLayoutDemo(String title) { super(title); setLayout(); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { setLayout(); GridLayoutDemo.this.validate(); } }; for (int i = 0; i < buttons.length; i++) { buttons[i] = new Button(names[i]); buttons[i].addActionListener(listener); add(buttons[i]); } setSize(250, 250); setVisible(true); } public void setLayout() { if (flag) setLayout(layout1); else setLayout(layout2); flag = !flag; } public static void main(String args[]) { new GridLayoutDemo("Hello"); } }