I am trying to create Menu to may 2D game in Java. But the game is not responding to pressed keyes. Menu is working, but when I choose new game in menu, game starts but it does not react to pressed keyes. But, when I remove menu, game is responding to pressed keys ... but when there is also menu, it is not responding. How to solve this problem ?
Here is Sokoban class:
package sokoban;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public final class Sokoban extends JFrame {
private Menu menu;
private Board board;
private static JFrame myFrame;
public Sokoban() {
InitUI();
}
public void InitUI() {
myFrame = new JFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(800,600);
myFrame.setLocationRelativeTo(null);
myFrame.setTitle("Labyrint");
myFrame.setResizable(false);
board = new Board();
menu = new Menu();
myFrame.add(menu);
//-----------
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);
//adding action listener to menu items
newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
menu.setVisible(false);
menu = null;
myFrame.add(board);
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
myFrame.setJMenuBar(bar);
bar.add(file);
myFrame.getContentPane();
myFrame.setVisible(true);
///------------------------------------
}
public static void main(String[] args) {
Sokoban sokoban = new Sokoban();
}
}
And this is game, part of Board.class (not responding to pressed keyes when Menu is working):
public class Board extends JPanel implements KeyListener {
public Board() {
addKeyListener(this);
setFocusable(true);
initWorld();
}
/* not importnant code for this problem here*/
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
if ((checkWallCollision(soko,LEFT_COLLISION)) == true) {
return;
}
if (checkBagCollision(LEFT_COLLISION)) {
return;
}
soko.move(-SPACE, 0);
score++;
celkove_score++;
} else if (key == KeyEvent.VK_RIGHT) {
etc.
.
.
.
}