Java实现满天星动案例
包含的小知识点有窗体、面板、数组、循环、线程等
效果图如下:
主要思想为在窗体上添加面板,然后再面板上作画,画出若干星星,最后通过move函数模拟星星移动。
代码如下:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class StarrySky extends JFrame {
public StarrySky() throws HeadlessException {
this.setTitle("满天星动");
this.setVisible(true);
this.setSize(800,700);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Background background = new Background();
this.add(background);
background.move();
}
public static void main(String[] args) {
StarrySky starrySky = new StarrySky();
}
}
class Background extends JPanel{
int x[] = new int[200];
int y[] = new int[200];
public Background() {
this.setBackground(Color.black);
for (int i = 0; i < x.length; i++) {
x[i] = (int) (Math.random() * (800-0) + 0);
y[i] = (int) (Math.random() * (700-0) + 0);
}
}
public void paint(Graphics graphics) {
super.paint(graphics);
for (int i = 0; i < x.length; i++) {
graphics.setColor( Color.white );
graphics.setFont( new Font( "", Font.PLAIN,10 ) );
graphics.drawString("✦", x[i], y[i]);
}
}
public void move() {
new Thread() {
public void run() {
while (true) {
for (int i = 0; i < x.length; i++) {
x[i] = x[i] < 0 ? 800: x[i] - 1;
y[i] = y[i] > 700 ? 0 : y[i] + 1;
}
try {
Thread.sleep(10);
}catch (InterruptedException e){
}
repaint();
}
}
}.start();
}
}