java的CardLayout2007-05-29 yycnet.yeah.net yyc译CardLayout允许我们在更复杂的拥有真正的文件夹卡片与一条边相遇的环境里创建大致相同于“卡片式对话框”的布局,我们必须压下一个卡片使不同的对话框带到前面来。在AWT里不是这样的:CardLayout是简单的空的空格,我们可以自由地把新卡片带到前面来。(JFC/Swing库包括卡片式的窗格看起来非常的棒,且可以我们处理所有的细节。)
1. 联合布局(Combining layouts)
下面的例子联合了更多的布局类型,在最初只有一个布局管理器被程序片或应用程序操作看起来相当的困难。这是事实,但如果我们创建更多的面板对象,每个面板都能拥有一个布局管理器,并且像被集成到程序片或应用程序中一样使用程序片或应用程序的布局管理器。这就象下面程序中的一样给了我们更多的灵活性:
//: CardLayout1.java// Demonstrating the CardLayoutimport java.awt.*;import java.applet.Applet;class ButtonPanel extends Panel {ButtonPanel(String id) {setLayout(new BorderLayout());add("Center", new Button(id));}}public class CardLayout1 extends Applet {Buttonfirst = new Button("First"),second = new Button("Second"),third = new Button("Third");Panel cards = new Panel();CardLayout cl = new CardLayout();public void init() {setLayout(new BorderLayout());Panel p = new Panel();p.setLayout(new FlowLayout());p.add(first);p.add(second);p.add(third);add("North", p);cards.setLayout(cl);cards.add("First card", new ButtonPanel("The first one"));cards.add("Second card", new ButtonPanel("The second one"));cards.add("Third card", new ButtonPanel("The third one"));add("Center", cards);}public boolean action(Event evt, Object arg) {if (evt.target.equals(first)) {cl.first(cards);} else if (evt.target.equals(second)) {cl.first(cards);cl.next(cards);} else if (evt.target.equals(third)) {cl.last(cards);} else return super.action(evt, arg);return true;}} ///:~
这个例子首先会创建一种新类型的面板:BottonPanel(按钮面板)。它包括一个单独的按钮,安放在BorderLayout的中央,那意味着它将充满整个的面板。按钮上的标签将让我们知道我们在CardLayout上的那个面板上。
在程序片里,面板卡片上将存放卡片和布局管理器CL因为CardLayout必须组成类,因为当我们需要处理卡片时我们需要访问这些句柄。
这个程序片变成使用BorderLayout来取代它的默认FlowLayout,创建面板来容纳三个按钮(使用FlowLayout),并且这个面板安置在程序片末尾的“North”。卡片面板增加到程序片的“Center”里,有效地占据面板的其余地方。
当我们增加BottonPanels(或者任何其它我们想要的组件)到卡片面板时,add()方法的第一个自变量不是“North”,“South”等等。相反的是,它是一个描述卡片的字符串。如果我们想轻击那张卡片使用字符串,我们就可以使用,虽然这字符串不会显示在卡片的任何地方。使用的方法不是使用action();代之使用first()、next()和last()等方法。请查看我们有关其它方法的文件。
在Java中,使用的一些卡片式面板结构十分的重要,因为(我们将在后面看到)在程序片编程中使用的弹出式对话框是十分令人沮丧的。对于Java 1.0版的程序片而言,CardLayout是唯一有效的取得很多不同的“弹出式”的窗体。