Java实现满天星动案例

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); // 点X退出
        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); // 0-799
            y[i] = (int) (Math.random() * (700-0) + 0); // 0-699
        }
    }

    public void paint(Graphics graphics) { // 作画方法,Graphics为画笔
        super.paint(graphics); // 把父类中的paint方法拿过来
        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() { // 在线程中相当于main函数,里面的代码可以被执行
                while (true) { // 死循环
                    for (int i = 0; i < x.length; i++) {
                        x[i] = x[i] < 0 ?  800: x[i] - 1; // 横坐标-1
                        y[i] = y[i] > 700 ? 0 : y[i] + 1; // 纵坐标+1
                    }
                    try {
                        Thread.sleep(10); // 线程睡眠
                    }catch (InterruptedException e){
                        //什么也不做
                    }
                    repaint(); // 重新作画
                }
            }
        }.start(); // 启动线程
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值