java小白 求大神指点控制小球移动的这段代码
package com.test4;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MoveBall2 extends JFrame{
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
MoveBall2 mb2=new MoveBall2();
}
public MoveBall2()
{
mp=new MyPanel();
this.add(mp);
this.addKeyListener(mp);
this.setSize(400, 400);
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
class MyPanel extends JPanel implements KeyListener
{
int x=100;
int y=10;
public void paint(Graphics g)
{
super.paint(g);
g.fillOval(x, y, 10, 10);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()==KeyEvent.VK_DOWN)
{
x--;
}else if(e.getKeyChar()==KeyEvent.VK_UP)
{
x++;
}else if(e.getKeyChar()==KeyEvent.VK_LEFT)
{
y--;
}else if(e.getKeyChar()==KeyEvent.VK_RIGHT)
{
y++;
}
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
这段代码有什么错 为什么按上下左右 小球都不动- -!求大神指点!!
java
import
class
string
null
------解决方案--------------------把e.getKeyChar()==KeyEvent换成e.getKeyCode()==KeyEvent就可以了,要细心些