JFrame 与 Fram 的区别之一 :如果把Frame改为JFrame那么星星不会依次出现,而是过一会儿才全部出现星星。
import java.awt.*;
public class MyTest1 {
public static void main(String[] args) {
Frame w = new Frame();
w.setSize(1366 , 768);
w.setBackground(Color.black);
Star star = new Star();
w.add(star);
w.show();
}
import java.awt.*;
import javax.swing.*;
public class Star extends JPanel{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0 , 0 , this.getWidth() , this.getHeight());
int x , y;
int red , green , blue;
g.setFont(new Font("" , Font.PLAIN , 36)); //使得星星变大
for(int i=1; i<=600; i++)
{
red = (int)(Math.random()*255); //设置星星的颜色
green = (int)(Math.random()*255);
blue = (int)(Math.random()*255);
g.setColor(new Color( red ,green , blue));
x = (int)(Math.random()*1336); //随机生成星星的位置
y = (int)(Math.random()*768);
g.drawString("*", x , y);
try
{
Thread.sleep(10);
}
catch(InterruptedExceptionex)
{
}
}
}
}
}