Derek Schuster
Derek Schuster

Reputation: 523

Trying to figure out the CardLayout

I'm trying to work out how to use the CardLayout but I keep getting "wrong parent for CardLayout" errors and such. I've never used CardLayout before and I can't seem to find a lot online. I just need to be able to switch between two panels on the frame. Thanks for any help. Here is my current code:

    Frame f = new Frame();
    CardLayout cardL = new CardLayout();
    JPanel cards = new JPanel(cardL);
    f.add(cards);
    StartPanel sp = new StartPanel();
    OtherPanel op = new OtherPanel();
    cards.add(sp, "Start");
    cards.add(op, "Other");

    cardL.show(sp, "Start");

    f.setVisible(true);

Upvotes: 1

Views: 53

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Change

cardL.show(sp, "Start");

to

cardL.show(cards, "Start");

As the CardLayout API will tell you, the first parameter of the show(...) method should be a reference to the container that uses the CardLayout.

Also:

  • Avoid mixing AWT (Frame) and Swing (JPanel). Instead use just Swing.
  • Safest to use String constants for your CardLayout keys. This way you avoid pernicious spelling and capitalization errors.
  • For similar errors, go to the Java API first before coming here. The solutions are often found there, and learning to do this is a good habit to get into.

Upvotes: 2

Related Questions