Key Listener遇到问题

时间:2017-05-18 03:58:36

标签: java swing

我正在为学校做一个破砖工作,而且我不明白我在使用keyListener做错了什么

import java.awt.*;

import java.awt.event。; import javax.swing。;

公共类委员会延伸JPanel {

private Brick bricks[];
private Ball ball;
private Timer timer;
private Paddle paddle;

public Board() {
    bricks = new Brick[Settings.TOTAL_BRICKS];
    //create a bunch of bricks
    for (int i =0;i<Settings.TOTAL_BRICKS;i++) {
        int row = (int) Math.floor(i / Settings.BRICK_COLUMNS);
        int col = i % Settings.BRICK_COLUMNS;

        int x = 10 + 70 * col;
        int y = 10 + 70 * row;
        bricks[i] = new Brick(x,y);
    }

    ball = new Ball(100,100);
    ball.setSpeed(2,2);
    paddle = new Paddle(100,315);



    timer = new Timer(20, new GameTick());
   timer.start();

   addKeyListener(new KeyboardManager());
   setFocusable(true);
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    for (int i = 0; i < Settings.TOTAL_BRICKS;i++) {
        g2d.drawImage(bricks[i].image,bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height,this);


    }
    g2d.drawImage(ball.image,ball.x,ball.y,ball.width,ball.height,this);
    g2d.drawImage(paddle.image,paddle.x,paddle.y,paddle.width,paddle.height,this);

}
public void padcolis()
{

}


private class KeyboardManager extends KeyAdapter {


    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode(); 
        if (key == KeyEvent.VK_LEFT) {
            paddle.setMovement(-1);
        }
        if (key == KeyEvent.VK_RIGHT) {
            paddle.setMovement(1);


    }
    }
    public void keyRelease(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            paddle.setMovement(0);
        }
    }

    }


private class GameTick implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
       ball.move();
       ball.coli();
       paddle.move();

      repaint();
   }

}

}

听到桨叶

mport java.awt.Image;

导入javax.swing.ImageIcon;

public class Paddle extends Sprite {

int moveXP, moveY, sloco=100;

public Paddle(int _x, int _y) {
    x = _x;
    y = _y;
    ImageIcon icn = new ImageIcon("paddle.png");
    image = icn.getImage();
    width = image.getWidth(null);
    height = image.getHeight(null);



}

public void setMovement(int i) {
    moveXP = i; 
}
public void move()
{
    if (moveXP == 0)
    {
        x = x + moveXP;
    }

    if (moveXP == 1)
    {
        x=x+moveXP;
        sloco ++;
    }
    if (moveXP ==-1)
    {
        x = x + moveXP;
        sloco --;
    }

}
public int colip(int i)
{
    int full = sloco + 75;
    return (full);
}

}

0 个答案:

没有答案