美轮美奂-随机绘制不同形状、色彩、大小、位置的图形

这或许是目前为止,我调试过的程序中输出效果最美的一个,”惊艳“程度比之万花筒有过之而无不及。

代码如下:

//Graphics Exercise 6.2
/*Create a program that draws 10 random filled shapes in random colors, positions and sizes
(Fig. 6.14). Method paintComponent should contain a loop that iterates 10 times. In each iteration,
the loop should determine whether to draw a filled rectangle or an oval, create a random color and
choose coordinates and dimensions at random. The coordinates should be chosen based on the panel’s
width and height. Lengths of sides should be limited to half the width or height of the window.*/
//Creating JFrame to display DrawPanel.
import javax.swing.JFrame;
import java.awt.Graphics; 
import javax.swing.JPanel;
import java.awt.Color;
import java.security.SecureRandom;

public class RandomShapes extends JPanel
{

	public void paintComponent(Graphics g)
	{
		   super.paintComponent(g);
		   int width = getWidth(); // total width   
		   int height = getHeight(); // total height
		   int rR=0;
		   int rG=0;
		   int rB=0;
		   int rShape=0;
		   int rX=0;
		   int rY=0;
		   int rWidth=0;
		   int rHeight=0;

		   final SecureRandom rn = new SecureRandom();
		   
		   for (int i = 10; i > 0;i--){

			   rR=rn.nextInt(256);
			   rG=rn.nextInt(256);
			   rB=rn.nextInt(256);
			   Color c=new Color(rR, rG, rB);
			   g.setColor(c);
			   
			   rShape=rn.nextInt(2);
			   rX=rn.nextInt(width);
			   rY=rn.nextInt(height);
			   rWidth=rn.nextInt(width/2);
			   rHeight=rn.nextInt(height/2);
			   
			   switch(rShape){
			   case 0:
			   g.fillOval(rX,rY,rWidth,rHeight);
			   break;
			   case 1:
			   g.fillRect(rX,rY,rWidth,rHeight);
			   }
			  }

	}

	
	public static void main(String[] args)
{
 // create a panel that contains our drawing
RandomShapes panel = new RandomShapes();
 
 // create a new frame to hold the panel
 JFrame application = new JFrame();
 
 // set the frame to exit when it is closed
 application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 application.add(panel); // add the panel to the frame      
 application.setSize(250, 250); // set the size of the frame
 application.setVisible(true); // make the frame visible    
} 
} 

 

运行截屏:

 

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值