在CardLayout中切换JPanel后,JFrame不响应按下的键

时间:2017-01-16 18:00:06

标签: java swing jpanel awt cardlayout

我是java的新手,我正在尝试创建一个Space Invaders游戏作为我的第一个“更大”的桌面项目。目前我已经为Space Invaders Tutorial添加了一些设计模式,但我一直在尝试添加一个菜单几天,我在网上发现的任何东西都没有。在实际找到一些有用的代码并将其添加到 SpaceInvaders 类后,我陷入困境。问题是,在我从主菜单中选择“新游戏”之后,游戏开始并且一切正常,除了玩家之外 - 它应该使用箭头键移动并使用alt进行拍摄,但它根本没有响应。 这是代码的一部分:

SpaceInvaders.java(主类)

public class SpaceInvaders extends JFrame implements ActionListener, Commons {

private static final long serialVersionUID = 1L;

JButton play = new JButton("New Game");
JButton scores = new JButton("High Scores");
JButton exit = new JButton("Exit");
JButton mainMenu = new JButton("Main Menu");

CardLayout layout = new CardLayout();

JPanel panel = new JPanel();
JPanel game = new JPanel();
JPanel menu = new JPanel(); 
Board board = new Board();

public SpaceInvaders() { 
    panel.setLayout(layout);        
    addButtons();

    setSize(BOARD_WIDTH, BOARD_HEIGTH);
    setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
    setTitle("Space Invaders");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    requestFocus();

}

private void addButtons() {

    play.addActionListener(this);
    scores.addActionListener(this);
    exit.addActionListener(this);
    mainMenu.addActionListener(this);

    //menu buttons
    menu.add(play);
    menu.add(scores);
    menu.add(exit);

    //background colors
    menu.setBackground(Color.BLACK);

    //adding children to parent Panel
    panel.add(menu,"Menu");
    panel.add(board,"Game");

    add(panel);
    layout.show(panel,"Menu");

}

public void actionPerformed(ActionEvent event) {

    Object source = event.getSource();

    if (source == exit) {
        System.exit(0);
    } else if (source == play) {
        //add(new Board());
        layout.show(panel, "Game");
    } 

}

public static void main(String[] args) {

    new SpaceInvaders(); 

}
}

Board.java

public class Board extends JPanel implements Runnable, Commons { 

private Dimension d;
private ArrayList aliens;
private Player player = Player.getInstance();
private Shot shot;

private int alienX = 150;
private int alienY = 5;
private int direction = -1;
private int deaths = 0;

private boolean ingame = true;
private final String expl = "../spacepix/explosion.png";
private final String alienpix = "../spacepix/alien.png";
private String message = "Game Over";

private Thread animator;

public Board() 
{
    //addKeyListener(new TAdapter());
    setFocusable(true);
    d = new Dimension(BOARD_WIDTH, BOARD_HEIGTH);
    setBackground(Color.black);          
    gameInit();
    getInputMap(IFW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
    getInputMap(IFW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
    getInputMap(IFW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "shoot");
    getInputMap(IFW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0), "alt");
    getActionMap().put("shoot", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int x = player.getX();
            int y = player.getY();
            if (ingame) { 
                if (!shot.isVisible())
                    shot = new Shot(x, y);
            } 
        }
    });
    getActionMap().put("left", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {                
            player.moveLeft();
        }
    });
    getActionMap().put("right", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            player.moveRight();
        }
    });
    getActionMap().put("alt", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    });

    setDoubleBuffered(true);
}

public void addNotify() {
    super.addNotify();
    gameInit();
}

public void gameInit() {

    //aliens work, so I deleted them form here

 //   player = new Player();
    shot = new Shot();

    if (animator == null || !ingame) {
        animator = new Thread(this);
        animator.start();
    }
}

//drawing aliens, players, bombs, shots and background also works

public void animationCycle()  {

    if (deaths == NUMBER_OF_ALIENS_TO_DESTROY) {
        ingame = false;
        message = "Game won!";
    }

    // player
    player.act();

    // player's shot
    if (shot.isVisible()) {
        Iterator it = aliens.iterator();
        int shotX = shot.getX();
        int shotY = shot.getY();

        while (it.hasNext()) {
            Alien alien = (Alien) it.next();
            int alienX = alien.getX();
            int alienY = alien.getY();

            if (alien.isVisible() && shot.isVisible()) {
                if (shotX >= (alienX) && 
                    shotX <= (alienX + ALIEN_WIDTH) &&
                    shotY >= (alienY) &&
                    shotY <= (alienY+ALIEN_HEIGHT) ) {
                        ImageIcon ii = 
                            new ImageIcon(getClass().getResource(expl));
                        alien.setImage(ii.getImage());
                        alien.setDying(true);
                        deaths++;
                        shot.die();
                    }
            }
        }

        int y = shot.getY();
        y -= 4;
        if (y < 0)
            shot.die();
        else shot.setY(y);
    }

// aliens
// bombs
// those work
}

public void run() {

    long beforeTime, timeDiff, sleep;

    beforeTime = System.currentTimeMillis();

    while (ingame) {
        repaint();
        animationCycle();

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;

        if (sleep < 0) 
            sleep = 2;
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            System.out.println("interrupted");
        }
        beforeTime = System.currentTimeMillis();
    }
    gameOver();
}

Player.java

public class Player extends Sprite implements Commons{

private static Player instance;
private final int START_Y = 280; 
private final int START_X = 270;

private final String player = "../spacepix/player.png";
private int width;

private Player() {

    ImageIcon ii = new ImageIcon(this.getClass().getResource(player));

    width = ii.getImage().getWidth(null); 

    setImage(ii.getImage());
    setX(START_X);
    setY(START_Y);
}

public static synchronized Player getInstance() {

    if(instance == null)
    {
        instance = new Player();
    }

    return instance;
}

public void act() {
    x += dx;
    if (x <= 2){
        x = 2;
    }             
    if (x >= BOARD_WIDTH - 2*width) {
        x = BOARD_WIDTH - 2*width;
    }
    //dx = 0;
}

public void moveLeft(){
    dx = -2;
}

public void moveRight(){
    dx = 2;
}
}

有人能告诉我该怎么做才能运作吗?我可能要么错误地初始化播放器,要么从一个菜单切换到另一个菜单,但我一直试图修复它几个小时,现在我已经没有想法了。提前谢谢。

P.S。我想在添加菜单之前添加一切正常。如果有人需要,我可以上传整个代码。

0 个答案:

没有答案