【转】Java-满天繁星案例

方法一:

package star;
import javax.swing.JFrame;
/**
 * 满天星星 * 300
 */
public class Stars {

	public static void main(String[] args) {
		
		JFrame jFrame = new Draw();
		jFrame.setSize(1336, 768);
		jFrame.setLocationRelativeTo(null);
		jFrame.setVisible(true);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}

}
package star;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Draw extends JFrame {
	
	//serialVersionUID 是最后的静态和私有变量
	//该变量的值将被JVM产生和用于序列化和对象的反序列化。
	private static final long serialVersionUID = 1L;
	
	public void paint(Graphics g) {
	
		int i = 0;
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, 1366, 768);
		
		while (i < 300) {
			
			g.setColor(Color.WHITE);
			g.drawString("*",(int)(Math.random()*1366),(int)(Math.random()*768));
			i++;
			
		}
		
		g.setColor(Color.WHITE);
		g.fillOval(800, 100, 100, 100);
		g.setColor(Color.BLACK);
		g.fillOval(780, 80, 100, 100);
			
	}
	
}

方法二:

package star;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * 满天星星 * 300
 */
public class MyStar {

	public static void main(String [] args){
	
		//创建窗体对象
		JFrame frame = new JFrame("MyStar");
		//sframe.setTitle("MyStar");
		//设置窗体的大小
		frame.setSize(1024,768);
		//设置位置居中
		frame.setLocationRelativeTo(null);
		//设置默认的关闭操作
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//创建MyPanel对象
		MyPanel panel = new MyPanel();
		//设置panel的背景颜色
		panel.setBackground(Color.BLACK);
		//将panel对象添加到frame上
		frame.add(panel);
		//显示窗体
		frame.setVisible(true);
		
	}
}

class MyPanel extends JPanel{
	
	//画的功能
	public void paint(Graphics g){
		
		super.paint(g);
		
		//设置一下画笔的颜色
		g.setColor(Color.WHITE);
		
		for(int i = 0; i < 300; i++){
			//Math.random()  [0,1)*1024
			g.drawString("*", 
					(int)(Math.random()*1024),
					(int)(Math.random()*768));
		}
		
		g.fillOval(800, 100, 100, 100);
		g.setColor(Color.BLACK);
		g.fillOval(780, 80,	100, 100);

	}
}

fillOval用法:
public abstract void fillOval(int x, int y, int width, int height)
x - 要填充椭圆的左上角的 x 坐标。
y - 要填充椭圆的左上角的 y 坐标。
width - 要填充椭圆的宽度。
height - 要填充椭圆的高度。

发布了53 篇原创文章 · 获赞 33 · 访问量 1280

猜你喜欢

转载自blog.csdn.net/qq_44458489/article/details/104825071