📄 starfield1.java
字号:
// StarField1.java
import java.awt.*;
import java.applet.Applet;
public class StarField1 extends Applet implements Runnable
{
Thread t;
int counter;
Color starColors [] = { Color.white, Color.darkGray, Color.lightGray,
Color.blue, Color.yellow };
public void start ()
{
if (t == null)
{
t = new Thread (this);
counter = 0;
t.start ();
}
}
public void stop ()
{
t = null;
}
public void run ()
{
Thread current = Thread.currentThread ();
while (t == current)
{
// Draw frame
repaint (); // This method causes the update method to be called.
// Pause
try
{
Thread.sleep (50);
}
catch (InterruptedException e) {}
// Manipulate counter
if (++counter > 500)
counter = 0;
}
}
public void paint (Graphics g)
{
// The following getClipBounds method call returns
// a rectangle that contains the dimensions of the
// clip (a rectangular portion of the drawing
// surface that must be redrawn, because of
// damage). Damage represents a "hole" in the
// drawing surface. It occurs when a window
// partially (or completely) obscures the drawing
// surface and then is removed. Because the
// surface's obscured pixels were replaced by the
// overlapping window, they must be redrawn.
// Rather than redraw the entire drawing surface,
// only the clip should be redrawn -- which also
// improves drawing performance.
Rectangle r = g.getClipBounds ();
// Redraw the clip area by filling all pixels with
// the color black. Any stars in this area will be
// wiped out.
g.setColor (Color.black);
g.fillRect (r.x, r.y, r.width, r.height);
}
// Return a random integer from 0 through limit - 1.
int rnd (int limit)
{
return (int) (Math.random () * limit);
}
public void update (Graphics g)
{
// When there are enough stars, redraw the background
// and erase visible stars.
if (counter == 0)
paint (g);
// Set the next star's color and draw this star.
g.setColor (starColors [rnd (starColors.length)]);
int x = rnd (getSize ().width);
int y = rnd (getSize ().height);
g.drawLine (x, y, x, y);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -