【发布时间】:2020-05-03 14:47:35
【问题描述】:
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 来改变 2 个矩形的坐标,但我似乎无法让它工作。我在实现 KeyListener 的类上收到编译错误“;预期”。我知道这个错误意味着什么我不知道在这种情况下如何解决它
【问题讨论】:
-
此行完全无效:
public Pong() implements KeyListener- 您需要将其移至类声明:class Pong extends JPanel implements KeyListener
标签: java class abstract-class keylistener