java满天星星代码_java实现满天星swing&awt

一起有两个类

1.MyStar.java

package day02;

import java.awt.Color;

import javax.swing.JFrame;

import javax.swing.JPanel;

/**

* 满天星

* @author BruceLong

* */

public class MyStar {

public static void main(String[] args) {

// TODO Auto-generated method stub

// 窗口 一切皆对象

// 老婆 小丽 = 新 老婆

// 闺蜜 小三 = 新 闺蜜

JFrame frame = new JFrame();

/**添加画纸*/

MyStarPanel panel =new MyStarPanel();

//panel.setBackground(Color.BLACK);

frame.add(panel);

/**

* 线程添加 */

Thread t = new Thread(panel);

t.start();

// 设置关闭模式

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// 设置窗体标题

frame.setTitle("满天星_BruceLong");

// 设置窗体大小

frame.setSize(800, 600);

// 设置居中

frame.setLocationRelativeTo(null);

// 设置窗口可见

frame.setVisible(true);

//

}

}

2.MyStarPanel.java

package day02;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import javax.swing.JPanel;

/**

* 画布类

* 1.继承 JPanel 画布类

* @author BruceLong

*

* */

// 公共的 类 类名

// 公共的人 王云龙

// private //私有的

// 王思聪 继承 王健林

public class MyStarPanel extends JPanel implements Runnable {

// 声明变量数组

int[] xx = new int[100];

int[] yy = new int[100];

// 构造方法

public MyStarPanel() {

for (int i = 0;i <100;i++) {

xx[i] = (int)(Math.random()*800);

yy[i] = (int)(Math.random()*600);

}

}

// 画笔方法

@Override

public void paint(Graphics g) {

// TODO Auto-generated method stub

super.paint(g);

// 2.设置背景颜色

this.setBackground(Color.BLACK);

// 6.画月亮 x,y,w,h

g.setColor(Color.pink);

g.fillOval(100, 100, 100, 100);

// 7.画月牙

g.setColor(Color.black);

g.fillOval(80, 80, 100, 100);

// 3.设置画笔颜色

g.setColor(Color.yellow);

// 4.设置字体大小

Font ft = new Font("微软雅黑",Font.BOLD,28);

g.setFont(ft);

// 5.满天星

for(int i = 0;i < 100;i++) {

// Math.random()随机函数0-1之间的double类型

// 0.99999 0.5*800 = 400.00(double)

// 400.00-->(int)强制转换---->400

//int x = (int)(Math.random()*800);

//int y = (int)(Math.random()*600);

int R = (int)(Math.random()*255);

int G = (int)(Math.random()*255);

int B = (int)(Math.random()*255);

Color color = new Color(R,G,B);

g.setColor(color);

g.drawString("*", xx[i], yy[i]);

}

// 1.画一颗小星星

//g.drawString("*", 30, 30);

}

@Override

public void run() {

// TODO Auto-generated method stub

while(true) {

// 1.修改坐标值

for(int i = 0;i <100;i++) {

int type = (int)(Math.random()*2);

if(type ==0) {

xx[i]++;

yy[i]++;

}else{

xx[i]--;

yy[i]++;

}

//xx[i]++;

//yy[i]++;

if(xx[i]>800) {

xx[i] = 0;

}

if(yy[i]>600) {

yy[i] = 0;

}

}

// 2.调用睡眠方法

try {

Thread.sleep(10);

} catch (Exception e) {

e.printStackTrace();

}

// 3.调用重绘方法

repaint();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值