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

JAVA小程序,我希望写一个窗口中出现三个球,但很囧地现在出现三个窗口,每个窗口一个球。。。这是怎么回事啊,应该怎么改?谢谢各位大侠了
悲剧的程序。。。

import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;

public class myyes extends Frame{
public static void main(String args[])
{ myyes yes=new myyes();

}
public myyes(){
Ball qiu1=new Ball(5,5);
Thread thread1=new Thread(qiu1);
Ball qiu2=new Ball(10,5);
Thread thread2=new Thread(qiu2);
Ball qiu3=new Ball(15,5);
Thread thread3=new Thread(qiu3);
thread1.start();
thread2.start();
thread3.start();
this.add(qiu1);
this.add(qiu2);
this.add(qiu3);
this.setSize(350,350);
this.setVisible(true);
this.setBackground(Color.BLACK);
this.validate();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}



class Ball extends Panel implements Runnable
{
int rgb=0;
Color color;
int x,y;
int dx=5,dy=5;
public Ball(int x,int y){
this.x=x;
this.y=y;
}
public void doColor(){
rgb=(int)(Math.random()*0xFFFFFF);
color=new Color(rgb);
}

public void paint(Graphics g){
super.paint(g);
g.setColor(color);
g.fillOval(x,y,50,50);
}

public void run(){
while(true){
if(x<=0) {dx=5;doColor();}  
else if((x+50)>=getWidth()) {dx=-5; doColor();}
if(y<=0) {dy=5;doColor();}
else if((y+50)>=getHeight()) {dy=-5; doColor();}
x=x+dx;
y=y+dy;  
repaint();
try{Thread.sleep(50);}
catch(InterruptedException e) {;}
}
}
}

------解决方案--------------------
因为你每个ball都是一个panel,自然就有三个窗口了,应该在frame上添加一个panel,然后在panel上画小球