简体   繁体   中英

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 JPanel s. 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 .

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


Some Points:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM