Java实现字符雨
package zfy;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.JFrame;
class RainCanvas extends Canvas implements Runnable{
private int width, height;
private Image offScreen; // 缓冲图片
private char[][] charset; // 随机字符集合
private int[] pos; // 列的起始位置
private Color[] colors = new Color; // 列的渐变颜色
public RainCanvas(int width, int height) {
this.width = width;
this.height = height;
// 生成ASCII可见字符集合
Random rand = new Random();
charset = new char;
for (int i = 0; i < charset.length; i++) {
for (int j = 0; j < charset.length; j++) {
charset = (char) (rand.nextInt(96) + 48);
}
}
// 随机化列起始位置
pos = new int;
for (int i = 0; i < pos.length; i++) {
pos = rand.nextInt(pos.length);
}
// 生成从黑色到绿色的渐变颜色,最后一个保持为白色
for (int i = 0; i < colors.length - 1; i++) {
colors = new Color(0, 255 / colors.length * (i + 1), 0);
}
colors = new Color(255, 255, 255);
setBackground(Color.BLACK);
setSize(width, height);
setVisible(true);
}
public void startRain() {
new Thread(this).start();
}
public void drawRain() {
if (offScreen == null) {
return;
}
Random rand = new Random();
Graphics g = offScreen.getGraphics();
g.clearRect(0, 0, width, height);
g.setFont(new Font("Arial", Font.PLAIN, 14));
//
for (int i = 0; i < charset.length; i++) {
int speed = rand.nextInt(3);
for (int j = 0; j < colors.length; j++) {
int index = (pos + j) % charset.length;
g.setColor(colors);
g.drawChars(charset, index, 1, i * 10, index * 10);
}
pos = (pos + 1) % charset.length;
}
}
@Override
public void update(Graphics g) {
paint(g);
}
public void run() {
while (true) {
drawRain();
repaint();
try {
Thread.sleep(50); // 可改变睡眠时间以调节速度
}
catch (InterruptedException e) {
System.out.println(e);
}
}
}
@Override
public void paint(Graphics g) {
// 当组件显示时检测是否要创建缓冲图片,在组件还不可见时调用createImage将返回null
if (offScreen == null) {
offScreen = createImage(width, height);
}
g.drawImage(offScreen, 0, 0, this);
}
}
public class ZFYTest extends JFrame{
private RainCanvas canvas = new RainCanvas(1366, 768);
public ZFYTest() {
super("ZFY");
setUndecorated(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
canvas = new RainCanvas(this.getWidth(), this.getHeight());
//canvas = new RainCanvas(800,600);
getContentPane().add(canvas);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
ZFYTest test = new ZFYTest();
test.canvas.startRain();
}
}
问个脑残的问题。。。这个怎么用 {:1_926:}这里玩java的比较少。。你会失望的 问大神一个问题。。。这个怎么用 无语 无法加载主类 看看怎么做到的 {:1_902:},收藏,试一下 不错 学习了!~ java菜鸟路过,,,,膜拜 java菜鸟路过 没看懂啊 呵呵
页:
[1]
2