zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java //PP2.16编写一个applet,画出北斗七星,并在夜空中添加一些其他的星星

JAVA 一个 添加 一些 编写 其他 画出 Applet
2023-09-11 14:22:21 时间

Java程序设计教程(第七版) John Lewis & William Loftus 电子工业出版社

 

PP2.16编写一个applet,画出北斗七星,并在夜空中添加一些其他的星星。

 

注意:
1. 在不同的IDE环境下,有部分代码可能需要变更。Java代码中的package和class名称自行设置,本文中采用Test。
2. 本程序应用到Applet,使用IDE时需要注意配置问题,具体请参考:https://blog.csdn.net/Trista_1999/article/details/103204112,如果还有其他配置问题,可自行搜索。
IDE工具:IntelliJ IDEA

 
代码块:


import javax.swing.JApplet;
import java.awt.*;
import java.util.Random;

public class Test extends JApplet {
    public void paint (Graphics page) {
        setBackground (Color.black);
        page.setColor(Color.white);

        //Basic star
        int[] xP = {100, 104, 106, 108, 112, 109, 110, 106, 102, 103};
        int[] yP = {100, 100, 97, 100, 100, 102, 108, 103, 108, 102};
        page.drawPolygon(xP, yP, 10);
        page.fillPolygon(xP, yP, 10);

        //Big Dipper
        int[][] xBD = new int[7][10];
        int[][] yBD = new int[7][10];
        int[] xAdd = {1000, 1050, 1350, 1400, 650, 400, 100};
        int[] yAdd = {350, 550, 550, 300, 250, 210, 290};
        for(int i=0; i<xAdd.length; i++){
            for(int j=0; j<xP.length; j++){
                xBD[i][j] = xP[j] + xAdd[i];
                yBD[i][j] = yP[j] + yAdd[i];
            }
            page.drawPolygon(xBD[i], yBD[i], 10);
            page.fillPolygon(xBD[i], yBD[i], 10);
        }

        //Connect the star with line
        page.drawLine(1106, 455, 1156, 655);
        page.drawLine(1156, 655, 1455, 655);
        page.drawLine(1455, 655, 1505, 405);
        page.drawLine(1505, 405, 1106, 455);
        page.drawLine(1106, 455, 755, 355);
        page.drawLine(755, 355, 505, 315);
        page.drawLine(505, 315, 205, 395);

        //Basic Small Star
        int[] xSmall = new int[10];
        int[] ySmall = new int[10];
        for(int i=0; i<xP.length; i++){
            xSmall[i] = xP[i]/2 - 100;
            ySmall[i] = yP[i]/2;
        }
        page.drawPolygon(xSmall, ySmall, 10);
        page.fillPolygon(xSmall, ySmall, 10);

        //Randomly Generated Stars
        Random rand = new Random();
        int randX, randY;
        int[] randSmallX = new int[10];
        int[] randSmallY = new int[10];
        for(int i=0; i<50; i++){
            randX = rand.nextInt(2000);
            randY = rand.nextInt(2000);
            for(int j=0; j<xP.length; j++){
                randSmallX[j] = xSmall[j] + randX;
                randSmallY[j] = ySmall[j] + randY;
            }
            page.drawPolygon(randSmallX, randSmallY, 10);
            page.fillPolygon(randSmallX, randSmallY, 10);
        }
    }
}

实现效果如下:
在这里插入图片描述