I’m trying to add a restart/replay functionality to my Java game.
Currently in my Game class (where the GUI and game gets initialized), I have:
init() method
Game() object
The Game object contains the GUI for the whole game window, and includes various objects (such as the actual game window, score board, a countdown timer, etc).
I would like to add a functionality where the game would restart (along with the countdown and scoring) if they click the restart button on the GUI or once the game ends.
I do realize that it’s best to re-instantiate the objects (scoring, countdown), however once instantiated they’re part of my GUI
i.e. add(scoreboard)
Is there a way to re-instantiate the objects without having to re-instantiate my GUI? Ideally I’d just like to re-instantiate the objects without having to re-open a completely new JFrame for the GUI. If someone could provide me with a sort of outline for the classes and methods I should have (and what they do), it’d be much appreciated.
Thanks!
Separate the data (model) from the GUI (view).
To take one example, your scoreboard is probably a JTable. The JTable would be in a view class, while the TableModel would be in a model class.
You do the same for all of your GUI components. For each component, you have a model of the component data in a model class.
Here’s a model class for a stopwatch GUI I put together. Without even seeing the GUI, you should be able to identify all of the data components that make up a stop watch.
Once separated, you put initialize methods in your model classes.
Edited to add: You pass an instance of the model class to your view class to generate the view. Here’s the main panel of the stop watch GUI.