Friday, January 9, 2015

Java Using Shapes Program



Display polygon using GUI

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);
   }
}

Display text in a rectangle

import java.awt.*;
import javax.swing.*
            public class Main extends JPanel 
{
   public void paint(Graphics g) 
  {
      g.setFont(new Font("",0,100));
      FontMetrics fm = getFontMetrics(new Font("",0,100));
      String s = "message";
      int x = 5;
      int y = 5;
      for (int i = 0; i < s.length(); i++) 
      {
         char c = s.charAt(i);
         int h = fm.getHeight();
         int w = fm.charWidth(c);
         g.drawRect(x, y, w, h);
         g.drawString(String.valueOf(c), x, y + h);
         x = x + w;
      }
   }
   public static void main(String[] args)
  {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.Exit_on_close);
      frame.setContentPane(new Main());
      frame.setSize(500, 700);
      frame.setVisible(true);
   }
}

Display different shapes

import java.awt.Shape;
import java.awt.geom.*;
public class Main
 {
   public static void main(String[] args) 
  {
      int x1 = 1, x2 = 2, w = 3, h = 4, 
      x = 5, y = 6, 
                  y1 = 1, y2 = 2, start = 3;
      Shape line = new Line2D.Float(x1, y1, x2, y2);
      Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);
      Shape oval = new Ellipse2D.Float(x, y, w, h);
      Shape rectangle = new Rectangle2D.Float(x, y, w, h);
                  Shape roundRectangle = new RoundRectangle2D.Float(x, y, w, h, 1, 2);
      System.out.println("Different shapes are created:");
   }
}

Display different shapes

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
            public class Main extends JPanel 
{
            public static void main(String[] a) 
   {
      JFrame f = new JFrame();
      f.setSize(400, 400);
      f.add(new Main());
      f.setDefaultCloseOperation(JFrame.Exit_on_close);
      f.setVisible(true);
   }
                public void paint(Graphics g) 
                {
      g.fillRect (5, 15, 50, 75);
   }
}

No comments:

Post a Comment