控制台程序。
网格布局管理器可以在容器的矩形网格中布局组件。
1 import javax.swing.*; 2 import java.awt.*; 3 import javax.swing.border.EtchedBorder; 4 5 public class TryGridLayout { 6 7 public static void createWindow(){ 8 JFrame aWindow = new JFrame("This is the Window Title"); 9 Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit 10 Dimension wndSize = theKit.getScreenSize(); // Get screen size 11 12 // Set the position to screen center & size to half screen size 13 aWindow.setSize(wndSize.width/2, wndSize.height/2); // Set window size 14 aWindow.setLocationRelativeTo(null); // Center window 15 aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 17 GridLayout grid = new GridLayout(3,4,30,20); // Create a layout manager 18 Container content = aWindow.getContentPane(); // Get the content pane 19 content.setLayout(grid); // Set the container layout mgr 20 EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED); // Button border 21 22 // Now add ten Button components 23 JButton button = null; // Stores a button 24 for(int i = 1 ; i <= 10 ; ++i) { 25 content.add(button = new JButton(" Press " + i)); // Add a Button 26 button.setBorder(edge); // Set the border 27 } 28 aWindow.pack(); // Size for components 29 aWindow.setVisible(true); // Display the window 30 } 31 32 public static void main(String[] args) { 33 SwingUtilities.invokeLater(new Runnable() { 34 public void run() { 35 createWindow(); 36 } 37 }); 38 } 39 }
应用程序窗口显示的最初大小由传送给JFrame对象的setBounds()方法的值来决定。如果希望窗口的大小能适合包含的组件,可以调用JFrame对象的pack()方法。在调用setVisible()方法之前,添加下面的代码:
aWindow.pack();