实现随机颜色的五角星按轨迹排列成圆,很简单
package second2d;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.geom.*;
public class Second2D extends Applet {
boolean isStandalone = false;
BorderLayout borderLayout1 = new BorderLayout();
//Get a parameter value
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
}
//Construct the applet
public Second2D() {
setBackground( Color.WHITE );
}
public void paint( Graphics g )
{
int xPoints[] =
{ 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };//五角星中点的X坐标
int yPoints[] =
{ 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };//五角星中点的Y坐标
Graphics2D g2d = ( Graphics2D ) g;//General2D类中g2d对象
GeneralPath star = new GeneralPath();//GeneralPath类中star对象
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );//指定五角星的第一个点
for ( int k = 1; k < xPoints.length; k++ )//绘制五角星,循环
star.lineTo( xPoints[ k ], yPoints[ k ] );
star.closePath();
g2d.translate( 200, 150 );//将原点位置移至(200,150)
for ( int j = 1; j <= 10; j++ ) {//绘制五角星,10个
g2d.rotate( Math.PI / 5.0 );
g2d.setColor(
new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );//random是Math里的随机数,因此在每次重绘的时候颜色都不一样
g2d.fill( star ); // 填充五角星
}
}
//Initialize the applet
public void init() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
//Component initialization
private void jbInit() throws Exception {
}
//Get Applet information
public String getAppletInfo() {
return " 参考Deitel著作《C How to Program》中相关程序_HeDi";
}
//Get parameter info
public String[][] getParameterInfo() {
return null;
}
}
效果是这样的:
