0
\$\begingroup\$

I am working on a simple 2D game in Java.

I want the game to have an opening screen, instructions screen, and the screen with the game itself.

From the opening screen the user presses buttons to get to the instructions screen or to the game screen. From the instructions the user should be able to get back to the opening screen. When a game is finished, the user is automatically sent back to the opening screen.

I want all of this to happen in the same JFrame. Each screen should be a class that extends JPanel.

What would be the best way to do that? I thought of making a method inside the Main class (the one with the main() method), the switches screens and can be called from anywhere in the program.

But how will this method switch screens? What would be the best way to replace the JPanels?

Thanks a lot

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can treat your "screens" as objects and only update one at a time. Combine that with state machines and you're good to go. \$\endgroup\$
    – Sidar
    Jan 17, 2014 at 8:00

1 Answer 1

5
\$\begingroup\$

The way I do it, not in java but in some sort of c#/c++ hybrid, is I have an engine class (similar to your main class), which holds a Screen object. The screen object is an abstract class with two main functions, update and draw. The engine has one screen which it just calls the Update and the Draw functions.

While I have no experience with it, I imagine the combination of your Main class and your JFrame would be similar to my Engine class and just handle calling the current screens functions.

Switching screens would be easy, just call Main.changeScreen, or something similar. Each screen would be its own class, you could have the base Screen class extend off JPanel if you needed. Having something like a pause screen would just pass a reference to the last screen, change the current screen to the pause screen and call the last screens draw function, then draw an overlay on top of that.

You could also have a stack of screens, where you only update/draw the top one, and going to the previous screen would simply be a Main.popScreen call. This might be more suitable to your exact scenario.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .