日期:2014-05-20  浏览次数:20632 次

【求助】线程控制小球移动
本帖最后由 lingyl1021 于 2014-03-08 20:36:02 编辑
刚接触java,想用线程控制小球的移动,大概是界面布局的问题,之后添加的小球总是覆盖了前一个,纠结了很久了,求教!!!
import java.awt.*;
import javax.swing.*;
class Ball extends Canvas
{
private Color color;
private int radius;
private int x;
private int y;
private int xSpeed;
private int ySpeed;
public void setXY(int x,int y){
this.x=x;
this.y=y;
repaint();
}
public void setColor(Color color){
this.color=color;
}
Ball(int radius){
setSize(10,10);
xSpeed=(int)(Math.random()*10)+5;
ySpeed=(int)(Math.random()*10)+5;
this.radius=radius;
x=(int)(Math.random()*100);
y=(int)(Math.random()*100);
color=(int)((Math.random())*10)>5?Color.blue:Color.green;
}
public void paint(Graphics g){
g.setColor(color);
g.fillOval(x,y,radius,radius);
}
public void setSpeed(int x,int y){
xSpeed=x;ySpeed=y;
}
public int xSpeed(){return xSpeed;}
public int ySpeed(){return ySpeed;}
public int X(){return this.x;}
public int Y(){return this.y;}
public int R(){return this.radius;}
public Color color(){return this.color;}
}

class  movement extends JFrame implements Runnable
{
Ball []ball=new Ball[2];
Thread []thread=new Thread[2];
movement(){
JPanel p=new JPanel();
thread[1]=new Thread(this);
thread[0]=new Thread(this);
ball[1]=new Ball(10);
ball[0]=new Ball(10);
p.add(ball[0]);
p.add(ball[1]);
this.setBounds(0,0,500,500);
this.add(p);
thread[0].start();
thread[1].start();
}
public void run(){
boolean flag=false;
while(true){
flag=false;
int num=Integer.MAX_VALUE;
Thread temp=Thread.currentThread();
for(int i=0;i<2;i++){
if(temp.equals(thread[i]))
{
flag=true;
num=i;
break;
}
}
if(flag){
if(ball[num].X()<=ball[num].R()||ball[num].X()>=400-ball[num].R()) 
ball[num].setSpeed(-1*ball[num].xSpeed(),ball[num].ySpeed());
if(ball[num].Y()>=500-4*ball[num].R()||ball[num].Y()<=ball[num].R())
ball[num].setSpeed(ball[num].xSpeed(),-1*ball[num].ySpeed());
ball[num].setXY(ball[num].X()+ball[num].xSpeed(),ball[num].Y()+ball[num].ySpeed());
try{Thread.sleep(50);}catch(Exception e){}
ball[num].repaint();
}
}
}

}
class exam
{
public static void main(String[] args) 
{
movement move=new movement();
move.setVisible(true);
move.setDefaultCloseOperation(3);
}
}

刚学习,代码有点糟,见谅!!跪求各种指教
各路大神,路过打个招呼吧,新人不容易的呀!!
------解决方案--------------------
引用:
Quote: 引用:

周末吧,大家都休息了。

还有你代码什么注释都没有,看的很不舒服,特别是移动那块全是i j k变量。

我感觉是你计算的问题。
代码这块不好意思了,我自己找到原因了,想问问怎么结贴


菜单栏上有结贴按钮
------解决方案--------------------
java-swing界面的编程,很少有人用,一般都是web开发,大多数都是不会,或者忘光了。