danielz
danielz

Reputation: 1767

How to start a JPanel after switching using CardLayout

So i am building a game with Swing. My main game is in a JPanel called Board while the the starting screen is a JPanel called StartScreen, i also made a JPanel called MainPanel with a CardLayout layout that i use to switch between the two panels.

MainPanel:

public class MainPanel extends JPanel {

JPanel startMenu, board;

public MainPanel(){

    setLayout(new CardLayout());
    startMenu = new StartMenu(this);
    board = new Board();
    add(startMenu, "startMenu");
    add(board, "board");
}
}

My problem is that once i initialize board, the constructor of the board panel is crating and starting a thread that will run the game, so by the time i switch to the game, the game has already started running. Is there a way to start the game only when the i switch to the second panel.

Right now this is the constructor for Board:

public Board(){
    addKeyListener(new KeyBoard());
    snake = new Snake();
    apple = new Apple();
    thread = new Thread(Board.this);
    thread.start();
}

Upvotes: 1

Views: 393

Answers (2)

camickr
camickr

Reputation: 324098

I was thinking of implementing a listener that gets called when the panel becomes visible .

You can use a ComponentListener and listen for componentShown or you can use an AncestorListener and listen for ancestorAdded.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

These suggestions may seem simplistic, but simplistic is what you likely need:

  • Don't start your game thread in the constructor.
  • When you swap to the game panel, start your thread there.
  • Also, you really should avoid using KeyListeners with Swing applications since it is considered a very low-level listener. Better to use Key Bindings if applicable.

e.g.,

public void swapToBoard() {
   cardLayout.show(mainContainer, "board");
   new Thread(boardInstance).start;
}

Edit
You state:

Yes but i would start the thread outside of the constructor, when i am switching JPanel i am just making the panel visible. I was thinking of implementing a listener that gets called when the panel becomes visible .

And that is what I believe is one problem with CardLayout -- I know of no such listener for this event, and if you look at its API, you'll see no such listener. You will likely have to hard-code it into your swap method.

Upvotes: 4

Related Questions