1

So I'm trying to change the panel for my JFrame after 3 seconds from the IntroPanel to the main menu panel. But it doesn't seem to remove the panel and add on the other one when I try to do it. I am not quite sure how I can fix this so I would take any advice to fix this. Thank you!

package gamecs245;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* @author ozhang
*/
public class View extends JFrame {

IntroPanel introP = new IntroPanel();
MainMenuPanel mainP = new MainMenuPanel();
CreditsPanel creditP = new CreditsPanel();
private Timer timer;
private int counter = 3;
private final int delay = 1000;

public View(){

startUp();
add(introP);

    ActionListener action = new ActionListener()
    {   
        @Override
        public void actionPerformed(ActionEvent event)
        {
            if(counter == 0)
            {
                timer.stop();
                System.out.println("Panel added");
                remove(mainP);
                add(mainP);

            }
            else
            {
                System.out.println(counter);
                counter--;
            }
        }
    };

    timer = new Timer(delay, action);
    timer.setInitialDelay(0);
    timer.start();



}

private void startUp(){
    setVisible(true);
    setFrameDimensions();
    setCloseOperation();
    setFrameTitle();
    setLocationRelativeTo(null);

}

private void removeIntro(){
    remove(introP);
}

private void setFrameDimensions(){
    setSize(600,400);
}

private void setCloseOperation(){
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private void actionPerformed(){

}

private void setFrameTitle(){
    setTitle("CS245 Project");
}

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 4
    Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Aug 08 '16 at 05:39
  • 4
    Read the section from the Swing tutorial on [How to Use Card Layout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) for a working example. Not only does the tutorial help with this problem but it can be used as a reference for other Swing basics. – camickr Aug 08 '16 at 05:42
  • 2
    in `actionPerfomed` you remove `mainP` and add it again. Mabye this is your problem – Nico T Aug 08 '16 at 06:12
  • 2
    Use CardLayout, but you have (LayoutManager hasn't implemented any notifier) to call revalidate() and repaint(), once time, after all changes to already visible Swing GUI are done, as last code lines in ActionListener – mKorbel Aug 08 '16 at 06:20

1 Answers1

0

Can you try this?

View.remove(<panel to hide>);
View.add(<panel to show>);
Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80