控制台程序。
边界布局管理器最多能在容器中放置5个组件。在这种布局管理器中,可以把组件放在容器的任意一个边界上,也可以把组件放在容器的中心。每个位置只能放置一个组件。如果把组件放置在已被占用的边界上,前一个组件就会被取代。要选择边界,应指定约束,约束可以是NORTH、SOUTH、EAST、WEST或CENTER。它们都是BorderLayout类中定义的final static常量。
1 import javax.swing.*; 2 import javax.swing.SwingUtilities; 3 import java.awt.*; 4 import javax.swing.border.EtchedBorder; 5 6 public class TryBorderLayout { 7 8 public static void createWindow(){ 9 JFrame aWindow = new JFrame("This is the Window Title"); 10 Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit 11 Dimension wndSize = theKit.getScreenSize(); // Get screen size 12 13 // Set the position to screen center & size to half screen size 14 aWindow.setSize(wndSize.width/2, wndSize.height/2); // Set window size 15 aWindow.setLocationRelativeTo(null); // Center window 16 aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 17 18 BorderLayout border = new BorderLayout(); // Create a layout manager 19 Container content = aWindow.getContentPane(); // Get the content pane 20 content.setLayout(border); // Set the container layout mgr 21 EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED); // Button border 22 23 // Now add five JButton components and set their borders 24 JButton button; 25 content.add(button = new JButton("EAST"), BorderLayout.EAST); 26 button.setBorder(edge); 27 content.add(button = new JButton("WEST"), BorderLayout.WEST); 28 button.setBorder(edge); 29 content.add(button = new JButton("NORTH"), BorderLayout.NORTH); 30 button.setBorder(edge); 31 content.add(button = new JButton("SOUTH"), BorderLayout.SOUTH); 32 button.setBorder(edge); 33 content.add(button = new JButton("CENTER"), BorderLayout.CENTER); 34 button.setBorder(edge); 35 36 aWindow.setVisible(true); // Display the window 37 } 38 39 public static void main(String[] args) { 40 SwingUtilities.invokeLater(new Runnable() { 41 public void run() { 42 createWindow(); 43 } 44 }); 45 } 46 }