编了一个小球移动代码,按上下左右键会自动移动,但是越按小球走动愉快,请高手帮忙看看:
public class Point implements Runnable{
int x;
int y;
int speed=5;
int direct;
public  Point(int x,int y,int direct) {
this.x=x;
this.y=y;
this.direct=direct;
}public  Point (int x,int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}public void run() {
while(true)
{
try {
Thread.sleep(50);
} catch (Exception e) {

e.printStackTrace();
}
switch(direct)
{
case 1:
moveup();

break;
case 2:
movedown();
break;
case 3:
moveleft();
break;
case 4:
moveright();
break;

}





}
}public void moveup()
{
y--;
}
public void movedown()
{
y++;
}
public void moveleft()
{
x--;
}
public void moveright()
{
x++;
}

}
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;import javax.swing.JFrame;
import javax.swing.JPanel;public class Test2 extends JFrame { public static void main(String[] args) {
Test2 test2=new Test2();


}
public  Test2() {
Mypanel mypanel=new Mypanel();
add(mypanel);

this.addKeyListener(mypanel);
this.setSize(400,360);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}}class Mypanel extends JPanel implements KeyListener
{
Point point=new Point(10,10);

public void paint(Graphics g) {
super.paint(g);
g.fillOval(point.getX(), point.getY(), 10, 10);
this.repaint();

}
public void keyPressed(KeyEvent e) {
Thread th1=new Thread(point);
th1.start();

if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
point.direct=4;



}else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
point.direct=3;

}else if(e.getKeyCode()==KeyEvent.VK_UP)
{
point.direct=1;

}else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
point.direct=2;


}



}
public void keyReleased(KeyEvent e) {


}
public void keyTyped(KeyEvent e) {


}}

解决方案 »

  1.   

    因为你每次按按钮,都有一个新的线程被启动,第一次按按钮,就一个线程在调用point的run方法,第二次,两个,...
      public Mypanel() {
        Thread th1 = new Thread(point); // 只要一个线程,在
        th1.start();
      }
      public void keyPressed(KeyEvent e) {    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
          point.direct = 4;
      

  2.   

    public class Mypanel extends JPanel implements KeyListener {
    Point point = new Point(10, 10);
    Thread th1 = new Thread(point);
    public Mypanel()
    {
    th1.start();
    }把线程定义在外面