Java基础之在窗口中绘图——绘制星星(StarApplet 1)

时间:2022-11-02 03:13:55

Applet程序。

可以把更复杂的几何形状定义为GeneralPath类型的对象。GeneralPath可以是直线、Quad2D曲线和Cubic2D曲线的结合体,甚至可以包含其他GeneralPath对象。

1、绘制星星:

 import java.awt.geom.*;

 public class Star {
// Return a path for a star at x,y
public static GeneralPath starAt(float x, float y) {
Point2D.Float point = new Point2D.Float(x, y);
p = new GeneralPath(GeneralPath.WIND_NON_ZERO);
p.moveTo(point.x, point.y);
p.lineTo(point.x + 20.0f, point.y - 5.0f); // Line from start to A
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 5.0f, point.y - 20.0f); // Line from A to B
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 5.0f, point.y + 20.0f); // Line from B to C
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 20.0f, point.y + 5.0f); // Line from C to D
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x - 20.0f, point.y + 5.0f); // Line from D to E
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x - 5.0f, point.y + 20.0f); // Line from E to F
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x - 5.0f, point.y - 20.0f); // Line from F to g
p.closePath(); // Line from G to start
return p; // Return the path
} private static GeneralPath p; // Star path
}

2、定义用来绘制星星的Applet:

 import javax.swing.*;
import java.awt.*; @SuppressWarnings("serial")
public class StarApplet extends JApplet {
// Initialize the applet
@Override
public void init() {
StarPane pane = new StarPane(); // Pane containing stars
getContentPane().add(pane); // BorderLayout.CENTER is default position
} // Class defining a pane on which to draw
class StarPane extends JComponent {
@Override
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g;
float delta = 60f; // Increment between stars
float starty = 0f; // Starting y position // Draw 3 rows of stars
for(int yCount = 0 ; yCount < 3 ; yCount++) {
starty += delta; // Increment row position
float startx = 0f; // Start x position in a row // Draw a row of 4 stars
for(int xCount = 0 ; xCount < 4 ; xCount++) {
g2D.draw(Star.starAt(startx += delta, starty));
}
}
}
}
}

3、HTML文件:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

 <html>     <head>  </head>
<body bgcolor="000000">
<center>
<applet
code = "StarApplet.class"
width = "360"
height = "240"
>
</applet>
</center>
</body>
</html>