Advertisement
fromMars

Draw Poolygon

Apr 24th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. /**Following example demonstrates how to draw a polygon by creating Polygon() object. addPoint() & drawPolygon() method is used to draw the Polygon.**/
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. public class Main extends JPanel {
  8.    public void paintComponent(Graphics g) {
  9.       super.paintComponent(g);
  10.       Polygon p = new Polygon();
  11.       for (int i = 0; i < 5; i++) p.addPoint((int) (
  12.          100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (100 + 50 * Math.sin(
  13.          i * 2 * Math.PI / 5)));
  14.       g.drawPolygon(p);
  15.    }
  16.    public static void main(String[] args) {
  17.       JFrame frame = new JFrame();
  18.       frame.setTitle("Polygon");
  19.       frame.setSize(350, 250);
  20.      
  21.       frame.addWindowListener(new WindowAdapter() {
  22.          public void windowClosing(WindowEvent e) {
  23.             System.exit(0);
  24.          }
  25.       });
  26.       Container contentPane = frame.getContentPane();
  27.       contentPane.add(new Main());
  28.       frame.setVisible(true);
  29.    }
  30. }
  31.  
  32. //================================example two========================
  33.  
  34. import java.awt.Color;
  35. import java.awt.Container;
  36. import java.awt.Graphics;
  37. import java.awt.Polygon;
  38. import java.awt.event.WindowAdapter;
  39. import java.awt.event.WindowEvent;
  40.  
  41. import javax.swing.JFrame;
  42. import javax.swing.JPanel;
  43.  
  44. public class Panel extends JPanel {
  45.    public void paintComponent(Graphics g) {
  46.       super.paintComponent(g);
  47.       Polygon p = new Polygon();
  48.       for (int i = 0; i < 5; i++) p.addPoint((int) (
  49.          100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (
  50.          100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
  51.      
  52.       g.drawPolygon(p);
  53.    }
  54.    public static void main(String[] args) {
  55.       JFrame frame = new JFrame();
  56.       frame.getContentPane().setBackground(Color.YELLOW);
  57.       frame.setTitle("DrawPoly");
  58.       frame.setSize(350, 250);
  59.       frame.addWindowListener(new WindowAdapter() {
  60.          public void windowClosing(WindowEvent e) {
  61.             System.exit(0);
  62.          }
  63.       });
  64.       Container contentPane = frame.getContentPane();
  65.       contentPane.add(new Panel());
  66.       frame.show();
  67.    }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement