我在CardLayout布局里,放入了几张卡片(孙悟空、猪八戒……)
通过“上一张”和“下一张”两个按钮进行控制
当到了最后一张的时候,继续点击“下一张”则会跳到第一张。
我是想,到了最后一张的时候,再点击“下一张”则依然停留在最后一张
Frame f=new Frame("CardLayout布局管理器");
String[] names={"孙悟空","猪八戒","沙和尚","唐僧","如来佛祖"};
Panel p1=new Panel();
CardLayout c=new CardLayout();
p1.setLayout(c);
for(int i=0;i<names.length;i++){
p1.add(names[i],new Label(names[i]));
}
Panel p=new Panel();
Button previous=new Button("上一张");
Button next=new Button("下一张");
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
c.next(p1);
}
});
是否需要自己定义变量进行记忆?

解决方案 »

  1.   

    你的需求好像只有定义变量来解决LayoutManager只负责布局,并不负责记忆组件
      

  2.   

    JDK 1.6 里面的源码,看上去有个 (i+1) % ncomponents, 所以内部已经是自动回到第一张,没有任何参数控制的,看来我们得自己写个变量来记住它。
         public void next(Container parent) {
    synchronized (parent.getTreeLock()) {
        checkLayout(parent);
                int ncomponents = parent.getComponentCount();
                for (int i = 0 ; i < ncomponents ; i++) {
                    Component comp = parent.getComponent(i);
                    if (comp.isVisible()) {
                        comp.setVisible(false);
                        currentCard = (i + 1) % ncomponents;
                        comp = parent.getComponent(currentCard);
                        comp.setVisible(true);
                        parent.validate();
                        return;
                    }
                }
                showDefaultComponent(parent);
    }
        }
      

  3.   

    我们的作法是最后一张时,把"下一张" disable掉。
      

  4.   

    下载 JDK 1.4+ 一般都自带源码,在 $JDK 安装后的目录下有个 src.zip。