1

Here is what I tried:

Dragged some JPanels onto a JFrame (using NetBeans inspector window).

In JFrame constructor, made all JPanels invisible using .setVisible(false), except the one I want to show first.

It works and I can easily go from one to another by using some buttons with actionPerformed and adding .setVisible(false) to the current card and .setVisible(true) to the one I want to see.

What I wanted to do now is to use CardLayout previous() and next(), similar to a browser's back/forward. I also would like to reach to a panel from different places, i.e., two panels can link to the same one, so previous panel wouldn't always be the same.

I tried using the following code in an actionPerformed inside JFrame class:

CardLayout cardLayout = (CardLayout) this.getLayout();
cardLayout.previous(this);

However, it doesn't work. What am I missing? Is this supposed to do what I'm looking for?

vitorsdcs
  • 682
  • 7
  • 32

2 Answers2

3

As you have set the layout of your JFrame to CardLayout, you will need to use the parent container when using its next() & previous() methods. For JFrame the parent container is the content pane. So change:

cardLayout.previous(this);

to

cardLayout.previous(getContentPane());
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Declare a variable String previousCard in your JPanel. When you go from CardA to CardB set previousCard variable to "CardA" or whatever the card's name is. So after setting this for all transitions from one card to other, the back buttons will always do the same thing.

cardLayouot.show(getContentPane(), previousCard);
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69