添加新对象时,Java KeyListener会消失

时间:2018-03-02 13:36:25

标签: java swing jframe keylistener pong

本论坛的全新内容。试图通过教程学习Java一段时间,直到现在我正在玩Swing制作Pong游戏时工作得很好..

我的问题是,当我尝试更改游戏中的关卡时,我的播放器的keylistener会停止工作。

我试图删除所有不必要的代码,希望我没有错过任何导致混乱的代码。 这就是我的Main-class中发生的事情,其中​​Data基本上是作为我的背景的JPanel,而Player是另一个JPanel,我将在main之后进入Player-class。

public class Main {
Data data = new Data(Color.RED);
Player player = new Player(700, 500, 20, 100);
public Main() throws InterruptedException{
    run(data, player);
            ballRecursive();
                    }

public void run(Data data) throws InterruptedException {
    frame.add(player, BorderLayout.WEST);
    frame.add(data, BorderLayout.CENTER);
}

public void ballRecursive() throws InterruptedException {
    if(playerScore.returnScore()==1){
        Data data = new Data(Color.GREEN);
        run(data);
}

这是我的播放器,试图删除此处不必要的任何内容以及:

public class Player extends JPanel implements ActionListener, KeyListener{
Timer timer = new Timer(5, this);

double yPos = 0, movementY = 0;
int squareSize = 60;

int yBound;

public Player(int w, int h, int width, int height) {
    timer.start();

    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
    yBound = (windowHeight - squareSize);

}
public void actionPerformed(ActionEvent e) {
    yPos += movementY;

    if (yPos < 0) {
        yPos = 0;
    } else if (yPos + squareSize > yBound) {
        yPos = yBound - squareSize;
    }

    repaint();
}

public void moveUp() 
{

    if (yPos == 0) 
    {
        movementY = 0;
    }
    movementY = -1;
}

public void moveDown() 
{
    if (yPos == yBound) 
    {
        movementY = 0;           
    }

    movementY = 1;
}

public void keyPressed(KeyEvent e) 
{
    int keyCode = e.getKeyCode();

    if (keyCode == KeyEvent.VK_UP) {
        moveUp();
    }

    if (keyCode == KeyEvent.VK_DOWN) {
        moveDown();
    }

}

public void keyReleased(KeyEvent e)
{
    int keyCode = e.getKeyCode();

    if (keyCode == KeyEvent.VK_UP) 
    {
        movementY = 0;
    }

    if (keyCode == KeyEvent.VK_DOWN) 
    {
        movementY = 0;
    }

0 个答案:

没有答案