Andrea Vaiuso
Andrea Vaiuso

Reputation: 11

Change instance of JPanel

i've created a JPanel with loaded components, called bkg, so I want to change it to SlideShow, that extends jpanel, and show it when i click on a button. this is the code called from the button:

public void startGame(){
    bkg.removeAll();
    bkg.revalidate();
    bkg.repaint();
    bkg = new SlideShow();
    contentPane.add(bkg, BorderLayout.CENTER);
}

In the SlideShow constructor I've created some test labels, but when I click the button, all of old bkg components disappear (as I want) but nothing from SlideShow components I placed in the costructor appears... How can change the bkg JPanel to another external class that extends JPanel?

Upvotes: 0

Views: 74

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Suggestions:

  1. Why remove/revalidate/repaint the bkg variable when you immediately replace the current object held by that variable with another?
  2. What you want to revalidate and repaint is the contentPane after replacing the bkg object after adding it to the contentPane.
  3. It's almost always better to use a CardLayout rather than manually swapping. The tutorial can be found here: CardLayout tutorial.
  4. Or since it looks like you're re-starting a game, perhaps then give the SlideShow class a reset() method, one that sets both its model and its visible state to its original conditions.

So

public void startGame(){

    // *** no need for this ***
    // bkg.removeAll();
    // bkg.revalidate();
    // bkg.repaint();


    bkg = new SlideShow();
    contentPane.add(bkg, BorderLayout.CENTER);

    // *** add this ***
    contentPane.revalidate();
    contentPane.repaint();
}

Or if you go the reset option, then the method would simplify to:

public void startGame(){
    bkg.reset();
}

However that reset method would be key, the details depending on the structure of the rest of your program.

Upvotes: 2

Related Questions