【JAVA语言程序设计基础篇】--图形--练习绘制多边形

来源:互联网 发布:象棋软件下载 编辑:程序博客网 时间:2024/05/22 07:01




package chapter15;import java.awt.Graphics;import java.awt.Polygon;import javax.swing.*;@SuppressWarnings("serial")public class DrawPolygon extends JFrame{public DrawPolygon(){setTitle("drawpolygon");add(new PolygonsPanel());}public static void main(String[] args) {DrawPolygon frame = new DrawPolygon();frame.setLocationRelativeTo(null);frame.setTitle("aaa");frame.setSize(300, 300);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}@SuppressWarnings("serial")class PolygonsPanel extends JPanel{protected void paintComponent(Graphics g){super.paintComponent(g);int xCenter = getWidth()/2;int yCenter = getHeight()/2;int radius = (int)(Math.min(getWidth(), getHeight())*0.4);Polygon polygon = new Polygon();  // Add points to the polygon    polygon.addPoint(xCenter , yCenter);    polygon.addPoint((int)(xCenter + radius *      Math.cos(2 * Math.PI / 6)), (int)(yCenter - radius *      Math.sin(2 * Math.PI / 6)));    polygon.addPoint((int)(xCenter + radius *      Math.cos(2 * 2 * Math.PI / 6)), (int)(yCenter - radius *      Math.sin(2 * 2 * Math.PI / 6)));    polygon.addPoint((int)(xCenter + radius *      Math.cos(3 * 2 * Math.PI / 6)), (int)(yCenter - radius *      Math.sin(3 * 2 * Math.PI / 6)));    polygon.addPoint((int)(xCenter + radius *      Math.cos(4 * 2 * Math.PI / 6)), (int)(yCenter - radius *      Math.sin(4 * 2 * Math.PI / 6)));    polygon.addPoint((int)(xCenter + radius *      Math.cos(5 * 2 * Math.PI / 6)), (int)(yCenter - radius *      Math.sin(5 * 2 * Math.PI / 6)));g.drawPolygon(polygon);//开画}}




0 0
原创粉丝点击