java - 对于我的代码,如何实现关键监听器?

标签 java class abstract-class keylistener

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

}

我是 jAVA 的初学者 我想实现一个按键监听器来更改两个矩形的坐标,但我似乎无法使其工作。我在实现 KeyListener 的类上收到编译错误,显示“;预期”。我知道该错误意味着什么,但在这种情况下我不知道如何解决

最佳答案

看起来您已将“implements KeyListener”放入 Pong 构造函数中。将实现移至类声明并从构造函数 Pong() 中提取 KeyListener/keyPressed 代码

公共(public)类 Pong 扩展 JPanel 实现 KeyListener

关于java - 对于我的代码,如何实现关键监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61576408/

相关文章:

Java PIT 类路径问题

c++ - 为什么我的计算出错了?

c# - 抽象类,如何避免代码重复?

javascript - 从 ES6 中的函数表达式访问类作用域

C# 静态类构造函数

c# - 重写抽象类中的方法

java - 在什么情况下父类(super class)不应该是抽象的?

java - 将重力应用于弹跳球

使用 JNA 从 Delphi 进行 Java 回调导致 VM 崩溃

java - Spring AMQP AcknowledgeMode.AUTO 工作缓慢