3

我创建了一个类,它有一个名为cards 的面板,它的布局是CardLAyout。我添加了卡片项目。在这个类中,我想通过调用哪个来创建一个单独的方法,布局切换到下一张卡片。

import java.awt.CardLayout;
import java.awt.Container;


public class cards 
{
      public Container cards;

//creating objects for other classes
public cricGUI gu;
public cricMainMenu mm;

public void cardsList()
{
    cards = new Container();
    cards.setLayout(new CardLayout());

    //adding panels and contentPanes from other classes.
    mm = new cricMainMenu();
    gu = new cricGUI();

    cards.add(mm.contentPane);
    cards.add(gu.pane);
}
public void getNextCard(Container x)
{

}

}

所以你可以看到我在我的卡片中添加了其他类的面板。我想要做的是创建 getNextCard() 方法,它将当前活动的面板作为它的参数。当我调用这个函数时,它应该用我的 CardLayout 列表中的下一个切换当前活动的面板。我怎样才能做到这一点?谢谢

4

1 回答 1

3

You may want to have a look at How to use CardLayout.

Basic principle is, that every card gets its own identifier (usually a String Constant). To switch to a specific card, you call

layout.show( container, identifier );

To implement a method like getNextCard() (better name would probably be switchToNextCard( container, identifier )) you could for example use an easy switch case construct like:

public void switchToNextCard( Panel container, String currentCard )
{
      switch ( currentCard )
      {
        case CARD1:
          layout.show( container, CARD2 );
          break;
        case CARD2:
          layout.show( container, CARD1 );
          break;
        default :
          throw IllegalArgumentException("Unsupported CardIdentifier.")
          break;
      }
}

In this Method CARD1 and CARD2 are your identifiers (String Constants) for your panels within your cardlayout. In this case it would switch back and forward between those two cards.

于 2012-07-31T15:46:47.613 回答