Search code examples
javaswinguser-interfacenetbeanscardlayout

CardLayout - How to use previous() and next() using NetBeans GUI Builder?


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?


Solution

  • 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);