Octagon.java
上传用户:topwell
上传日期:2022-05-30
资源大小:1k
文件大小:1k
源码类别:

网络编程

开发平台:

DOS

  1. import java.awt.*;
  2. import javax.swing.*;
  3. public class Octagon extends JFrame{
  4.   public Octagon(){
  5.     add(new OctagonPanel());
  6.   }
  7.   public static void main(String[] args){
  8.     Octagon frame = new Octagon();
  9.     frame.setTitle("Octagon");
  10.     frame.setLocationRelativeTo(null);
  11.     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12.     frame.setSize(300, 300);
  13.     frame.setVisible(true);
  14.   }
  15. }
  16. class OctagonPanel extends JPanel{
  17.   protected void paintComponent(Graphics g){
  18.     super.paintComponent(g);
  19.     //Get the center point and radius
  20.     int xCenter = getSize().width / 2;
  21.     int yCenter = getSize().height / 2;
  22.     int radius = (Math.min(xCenter, yCenter) - 20);
  23.     System.out.println("xCenter = " + xCenter + ", yCenter = " + yCenter +
  24.       ", radius = " + radius);
  25.     Polygon octagon = new Polygon();
  26.     for(int i = 0; i < 8; i++){
  27.       double angle =  Math.PI * i * 45.0 / 180;
  28.       int x = (int)(xCenter - radius * Math.cos(angle));
  29.       int y = (int)(yCenter - radius * Math.sin(angle));
  30.       octagon.addPoint(x, y);
  31.       System.out.println("x = " + x + ", y = " + y);
  32.     }
  33.     // Draw a octagon
  34.     g.drawPolygon(octagon);
  35.   }
  36. }