这是我用来让一个黑色实心小球根据上下左右动的程序。。。可是设计完成后运行时输入指令无效,求解释importjava.awt.*;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListe...
这是我用来让一个黑色实心小球根据上下左右动的程序。。。可是设计完成后运行时输入指令无效,求解释
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class MovingBall extends JFrame{
MyPanel mp=null;
public MovingBall(){
mp= new MyPanel();
this.add(mp);
this.setSize(400,300);
this.setTitle("Moving Ball");
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MovingBall movingBall= new MovingBall();
}
}
class MyPanel extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint(Graphics g){
super.paint(g);
g.fillOval(x,y,10,10);
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y++;
}
else if(e.getKeyCode()==KeyEvent.VK_UP){
y--;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT){
x--;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x++;
}
this.repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
展开