user3726660
user3726660

Reputation: 1

Issue with adding a JPanel onto another JPanel

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.

Upvotes: 0

Views: 38

Answers (2)

Braj
Braj

Reputation: 46841

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


Some Points:

Upvotes: 1

Revive
Revive

Reputation: 2248

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

Upvotes: 0

Related Questions