建立MyStar和MyStarpanel的.java的文件
/**
* 满天星的画布
*/
public class MyStarPanel extends JPanel implements Runnable {
/*1.变量声明区域*/
int[] xx = new int[100];
int[] yy = new int[100];
/*2.构造方法区域 静态代码块*/
public MyStarPanel(){
for (int i =0;i<100;i++){
xx[i]=(int)(Math.random()*900);
yy[i]=(int)(Math.random()*700);
}
}
/*3.绘制区域-JPanel*/
@Override
public void paint(Graphics g) {
super.paint(g);
//3.1 设置背景颜色
this.setBackground(Color.BLACK);
// 3.5月亮
g.setColor(Color.pink);
g.fillOval(100,100,100,100);
// 3.6月牙
g.setColor(Color.black);
g.fillOval(80,80,100,100);
//g是画笔
//设置字体样式
Font ft = new Font("微软雅黑",Font.BOLD,28);
g.setFont(ft);
//3.3绘制小星星
g.setColor(Color.YELLOW);
//3.4绘制满天星
for(int i = 0;i<100;i++){
//五颜六色
int R = (int)(Math.random()*255);
int G = (int)(Math.random()*255);
int B = (int)(Math.random()*255);
g.setColor(new Color(R,G,B));
g.drawString("*",xx[i],yy[i]);
}
//绘制小星星
g.drawString("*",100,100);
}
/*4.运行区域-Runnable*/
@Override
public void run() {
// 4.2睡眠方法
//4.3重绘重新调用paint
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
}
package cn.edu.sqxy.day16;
import javax.swing.*;
/**
* 满天星
*/
public class MyStar {
public static void main(String[] args) {
//1.创建窗口对象
JFrame frame = new JFrame("满天星");
//2.设置窗口大小
frame.setSize(900,700);
//3.设置窗口的居中显示 null默认是居中
frame.setLocationRelativeTo(null);
//4.设置关闭模式
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//5.设置窗口可见
frame.setVisible(true);
//6.创建自定义画布对象
MyStarPanel panel = new MyStarPanel();
//7.添加画布对象
frame.add(panel);
//8.创建线程对象绑定画布对象
Thread t = new Thread(panel);
t.start();
}
}