我如何在我的代码中实现一个键监听器?

问题描述 投票:0回答:1
 public class Pong extends JPanel  {

    int x=0;
    int y=0;
    int a;
    int b;

    int border=30;
    boolean balldown=true;
    boolean ballright=true;
    int bounce=0;

    private void moveBall(){
        if (balldown==true){
            y++; 
            bounce++;
        }

        if (balldown==false){
            y--;
            bounce++;
        }

        if(y==getHeight()-border){
            balldown=false;
            bounce++;
        }

        if(y==0){
            balldown=true;
            bounce++;
        }

        if (ballright==true){
            x++;          
        }

        if (ballright==false){
            x--;
            bounce++;
        }

        if(x==getWidth()-30){
            ballright=false;
            bounce++;
        }
        if(x==0){
            ballright=true;
            bounce++;
        }   
    }

    @Override
    public void paint(Graphics g){

        super.paint(g);

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 1080, 760);

        g.setColor(Color.WHITE);
        g.fillOval(x, y, 30, 30);

        g.setColor(Color.WHITE);
        g.fillRect(0, a, 30, 200);

        g.setColor(Color.WHITE);
        g.fillRect(980, b, 30, 200);

        g.fillRect(520, 0, 10, 760);
    }

    public  Pong() implements KeyListener {

     void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if (key == KeyEvent.VK_UP) {
            a += 10;
            System.out.println("++++");
            return;
        }

        if (key == KeyEvent.VK_DOWN) {
            a -= 10;

        }
    }

}
public static void main(String[] args) throws InterruptedException {

    JFrame frame = new JFrame("Pong");
    frame.setSize(1024,760);
    frame.setVisible(true);
   // frame.createBufferStrategy(3);
    //BufferStrategy strategy=frame.getBufferStrategy();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Pong game=new Pong();
    frame.add(game);

    while(true){
        game.moveBall();
        game.repaint();
         Thread.sleep(1);
   }
 }

}

我是一个javai初学者,想实现一个keylistener,改变2个矩形的坐标,但我似乎不能让它工作。我得到的编译错误是";预期 "在实现KeyListener的类上。我知道这个错误意味着什么,但我不知道在这种情况下如何解决它。

java class abstract-class keylistener
1个回答
0
投票

看起来你把" implements KeyListener "放到了 Pong contructor 中。把 implements 移到类声明中,然后把 KeyListener keyPressed 的代码从构造函数 Pong() 中拉出来。

public class Pong extends JPanel implements KeyListener

© www.soinside.com 2019 - 2024. All rights reserved.