Java如何使用GUI繪製多邊形?

2019-10-16 22:26:53

在Java的GUI程式設計中,如何使用GUI繪製多邊形?

以下範例演示如何通過建立Polygon()物件來繪製多邊形。addPoint()drawPolygon()方法用於繪製多邊形。

package com.yiibai;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DisplayPolygon 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 DisplayPolygon());
        frame.setVisible(true);
    }
}

上述程式碼範例將產生以下結果。

範例-2

以下是使用GUI繪製多邊形的另一個範例。

package com.yiibai;

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 DisplayPolygon2 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("使用GUI繪製多邊形");
        frame.setSize(350, 250);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        Container contentPane = frame.getContentPane();
        contentPane.add(new DisplayPolygon2());
        frame.show();
    }
}

上述程式碼範例將產生以下結果。