控制台程序。
卡片布局管理器会生成一叠组件——一个组件放在另一个组件的上面。添加到容器中的第一个组件在堆栈的顶部,因此是可见的,添加的最后一个组件在堆栈的底部。使用默认的构造函数CardLayout()可以创建CarLayout对象,也可以把水平和垂直间距指定为构造函数的参数。
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 }
需要一个包含如下内容的HTML文件来执行这个applet:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 3 <html> 4 <head> </head> 5 <body bgcolor="000000"> 6 <center> 7 <applet 8 code = "TryCardLayout.class" 9 width = "500" 10 height = "300" 11 > 12 </applet> 13 </center> 14 </body> 15 </html>
使用appletviewer运行程序。