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

时间:2014-06-10 15:25:15

标签: java swing jpanel

我正在制作游戏而且我已经拥有它所以当我按下我制作的菜单上的按钮时,它会加载游戏。游戏和菜单都是JPanel。问题是,当我单击按钮它加载JPanel但键盘输入不起作用。为什么会发生这种情况? 这是我的代码:

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();
   }

}

点击该按钮后,会在当前JPanel之上添加JPanel

2 个答案:

答案 0 :(得分:1)

阅读在同一背景下提出的帖子JPanel not responding to keylistener


一些要点:

答案 1 :(得分:0)

尝试添加play.setFocusable(true);和play.requestFocus();在您创建新的JPanel之后。这应该将焦点放在新面板中并允许键盘输入