How do I remove a JPanel from a JFrame in a 2D tile game (Java)?
Hello.
I won't post the whole code here because it's too complicated, but I'll try to explain it roughly.
I'm currently working on a game made of 2D tiles.
The game has the following classes (which are relevant here):
MainClass: The main class where the code begins. This is where the JFrame is created, initialized, etc.
GameField: This is where the game takes place. The character moves here like in the old NES Legend of Zelda game. The thread method named Run() is located here. There are also Update() and Redraw() methods, each of which updates the game data and then displays the updated data on the GameField. This happens 60 times per second.
Player: In this class the player is hired.
Now to the problem.
I want that after the player has collected a certain number of items in the field, the GameField is removed from the JFrame using frame.remove(GameField); and that it is replaced with other JPanels that display the end of the game's story.
I have all the logic for the player, how he moves, how he picks up things (this is handled in the Player class) etc. What I just want to know is how to remove the GameField from the JFrame, which I haven't been able to do so far.
Thanks in advance.
With the remove-Method you can remove components from a container. Thereafter, however, the surface must be redrawn. With the call of revalidate you give that the hierarchy of the frame no longer valid and must therefore be rebuilt.
If you want to hang in a new panel, do it before revalidate– Call.
You could also simply overwrite/cover the surface of the panel. This would not have to redraw the window.
A CardLayout to use could also be a solution option.
But I can’t just do this in the MainClass because when the GameField is started, it won’t get out so easily.
You only need a reference to the JFrame– Object shows. Either you pass on one to GameField– Object (e.g. via the constructor) or you use the getParent-Method.