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.