Quite green regarding javas component-stuff etc so please excuse me if information given by me isn't enough!
Considet the code below. Adding menu and menu showing in frame, no problem. I want when gameOn() is called to remove the menu and instead start the game. The code below only makes the Frames surface "blank", no gamepanel added.
Any thoughts/suggestions on how to fix it? The MenuPanel has a mouselistener.
public class GameFrame extends JFrame {
private MenuPanel mp; //extends JPanel
private GamePanel gp; //extends JPanel
public GameFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(GameFrame.XSIZE, GameFrame.YSIZE));
setLocationRelativeTo(null);
setVisible(true);
mp = new MenuPanel(this);
add(mp);
}
public void gameOn() {
remove(mp);
GamePanel gp = new GamePanel(5);
add(gp);
}
}
Instead of trying to add an remove components, use a
CardLayout
When
gameOn()
is called, themenu
will get pushed to the back, and thegame
to the front.This way you don't have to keep adding and removing
Here's an example you can run
After adding the GamePanel, do
validate();
}
You'll need to
repaint()
after you remove one panel and add another,setVisible(true)
should be done after you've added your componen ts to the frame and I recommend doing heavy UI changes like that on the EDT thread to avoid interference.