简体   繁体   English

将JPanel添加到另一个JPanel的问题

[英]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. 游戏和菜单均为JPanel The problem is when I click the button it loads the JPanel but the keyboard input doesn't work. 问题是,当我单击该按钮时,它将加载JPanel,但是键盘输入不起作用。 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 . 当单击该按钮,它增加了一个JPanel在当前的顶部JPanel

Read this post JPanel not responding to keylistener that is asked in the same context. 阅读这篇文章, JPanel无法响应在相同上下文中被要求的键侦听器


Some Points: 一些要点:

Try adding play.setFocusable(true); 尝试添加play.setFocusable(true); and play.requestFocus(); 和play.requestFocus(); after you have created the new JPanel. 创建新的JPanel之后。 This should put the focus in the new panel and allow keyboard input 这应该将焦点放在新面板上并允许键盘输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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