Java 示例 - 使用 GUI 显示多边形

  • 问题描述

    如何使用 GUI 绘制多边形?
  • 解决方案

    以下示例演示如何通过创建 Polygon() 对象来绘制多边形。addPoint() & drawPolygon() 方法用于绘制多边形。
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Main extends JPanel {
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Polygon p = new Polygon();
          for (int i = 0; i < 5; i++) p.addPoint((int) (
             100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (100 + 50 * Math.sin(
             i * 2 * Math.PI / 5)));
          g.drawPolygon(p);
       }
       public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.setTitle("Polygon");
          frame.setSize(350, 250);
          
          frame.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                System.exit(0);
             }
          });
          Container contentPane = frame.getContentPane();
          contentPane.add(new Main());
          frame.setVisible(true);
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    Polygon is displayed in a frame.
    
    下面是另一个使用 GUI 绘制多边形的示例。
    
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Panel extends JPanel {
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Polygon p = new Polygon();
          for (int i = 0; i < 5; i++) p.addPoint((int) (
             100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (
             100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
          
          g.drawPolygon(p);
       } 
       public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.getContentPane().setBackground(Color.YELLOW); 
          frame.setTitle("DrawPoly");
          frame.setSize(350, 250);
          frame.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                System.exit(0);
             } 
          }); 
          Container contentPane = frame.getContentPane();
          contentPane.add(new Panel());
          frame.show();
       }
    }
    
    上面的代码示例将产生以下结果。
    
    Polygon is displayed in a frame.