0

I am making a game and I have it so when I press a button on a menu I made, it loads the game. Both the game and the menu are JPanels. The problem is when I click the button it loads the JPanel but the keyboard input doesn't work. Why might this be happening? Here is the my code:

public class Menu extends JPanel  {
    static boolean load = false;
    JButton play = new JButton("play");
    GamePanel panel = new GamePanel();

    public Menu(){
        setLayout(new FlowLayout());
        add(play);


        setVisible(true);  
        play.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                    Runner.panel.setPreferredSize(new Dimension(570,700));
                    add(Runner.panel,0,0);
                    //repaint();
                    validate();
            }
       });
   }

   public void paint(Graphics g){
       super.paint(g);
       Graphics2D g2d = (Graphics2D) g;
       draw(g2d);

   }

   public void draw(Graphics2D g2d){

       g2d.drawImage(getBulletImage(),0,0,null);

   }



   // gets the image file for the player class
   public Image getBulletImage(){
       ImageIcon ic = new ImageIcon("Menu.png");
       return ic.getImage();
   }

}

When the button is clicked in, it adds a JPanel on top of the current JPanel.

Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65

2 Answers2

1

Read this post JPanel not responding to keylistener that is asked in the same context.


Some Points:

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

Try adding play.setFocusable(true); and play.requestFocus(); after you have created the new JPanel. This should put the focus in the new panel and allow keyboard input

Revive
  • 2,248
  • 1
  • 16
  • 23
  • 2
    +1 for making the panel focusable. -1 for suggesting requestFocus(). Don't use requestFocus(). The proper method to use is `requestFocusInWindow()` – camickr Jun 10 '14 at 15:56