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

时间:2022-02-03 18:33:22

这或许是目前为止,我调试过的程序中输出效果最美的一个,”惊艳“程度比之万花筒有过之而无不及。美轮美奂-随机绘制不同形状、色彩、大小、位置的图形


代码如下:

//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    
} 
} 


运行截屏:


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