Hello guys,
I'm programming a little game and tried to create a menu for it. The menu is like this:
New Game, Load and Exit are JButtons.
When I run the program I see that screen but when i press New Game I want the menu JPanel to be replaced for the game JPanel. I was able to do it the problem is that the KeyListener on my Game panel doens't work. Any way i can do it having the KeyListener working when menu JPanel is removed?
Java Code
public class GameFrame extends JFrame{
private GameMenu menu;
private GameCanvas canvas;
public GameFrame(String name, int width, int height) {
super(name);
menu = new GameMenu(this, width,height);
add(menu);
canvas = new GameCanvas(width, height);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
//When New Game button is pressed this metod is called.
protected void beginGame() {
setContentPane(canvas);
canvas.launchGame();
canvas.repaint();
validate();
}
}
public class GameCanvas extends JPanel implements KeyListener{
protected GameCanvas(int width, int height) {
super();
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
addKeyListener(this);
setFocusable(true);
}
}
Please help me!