0

我正在关注与关键事件有关的编码教程,所有代码看起来都正确,但由于某种原因,出现了一个我无法修复的错误。也许我需要的只是另一双眼睛来扫描它并发现我的错误。这是代码。有错误的代码行两侧有 2 个星号。错误告诉我那个“;” (分号)应该在“(”和“)”所在的地方......这有什么意义?我也会发一张图片。

package com.Bench3.myGame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Keying extends JPanel{

public Rectangle character;

public int charW = 24;
public int charH = 36;

public boolean right = false;
public boolean left = false;

public Keying(Display f, Images i){
    character = new Rectangle(180, 180, charW, charH);

    f.addKeyListener(new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            if(e.getKeyCode() == KeyEvent.VK_D){
                right = true;
            }
            if(e.getKeyCode() == KeyEvent.VK_A){
                left = true;
                }

            **public void keyReleased(KeyEvent e)**{
                if(e.getKeyCode() == KeyEvent.VK_D){
                    right = false;
                }
                if(e.getKeyCode() == KeyEvent.VK_A){
                    left = false;
                }
            }
        }
    });     
}
public void paintComponent(Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.BLACK);
    g.setColor(Color.WHITE);
    g.fillRect(character.x, character.y, character.width, character.height);

    if(right){
        character.x += 1;
    }
    if(left){
        character.x -= 1;
    }
    repaint();
}

} 这是近距离的错误。 希望它有帮助谢谢!

4

2 回答 2

4

您忘记关闭先前方法 ( ) 的花括号keyPressed():-

public void keyPressed(KeyEvent e){
        if(e.getKeyCode() == KeyEvent.VK_D){
            right = true;
        }
        if(e.getKeyCode() == KeyEvent.VK_A){
            left = true;
            }
} // missing
于 2012-10-20T05:35:39.080 回答
2

keyPressed()方法}剩余。

public void keyPressed(KeyEvent e){
        if(e.getKeyCode() == KeyEvent.VK_D){
            right = true;
        }
        if(e.getKeyCode() == KeyEvent.VK_A){
            left = true;
            }
}// you missed `}`
于 2012-10-20T05:36:03.777 回答