Monday, 28 May 2012

Combine Multiple Shapes in Java using 2DGraphics

Constructive area geometry is a fancy name for combining shapes. Two or more shapes can be combined using different rules or operations, much the way numbers can be combined in an equation. The 2D API supports four different operations for combining the areas of two shapes:
addition (union) - The addition of two shapes is the area covered by one or both of the shapes.
intersection - The intersection of two shapes is the area that is covered by both shapes simultaneously.
subtraction - The result of subtracting one shape from another is the area covered by one that is not covered by the other.
exclusive or - The exclusive or operator is the inverse of the intersection operator. In other words, the exclusive or of two shapes is the area that is covered by one or the other of the shapes. But it does not include the area covered by both.
Shapes looking After combining
 The following interactive example, CombiningShapes, demonstrates the four area operators. It displays two shapes and a combo box that allows you to choose which area operator will be used to combine the shapes. All of this is accomplished in two methods and one constructor. The main()
method sets up a frame window to contain the example. CombiningShapes's constructor creates the two shapes and a combo box that holds the area operator names. Finally, the paint()method combines the two shapes according to the selected operator and draws the result.Screenshot of the output of code written is shown below
Screenshots of output in different cases combined together

DOWNLOAD source Java file from Mediafire
DOWNLOAD ApplicationFrame source code from Mediafire as without this program won't compile.
You can also view code from below.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class CombiningShapes extends JComponent {

public static void main(String[] args) {
    ApplicationFrame f = new ApplicationFrame("CombiningShapes v1.0");
    f.add(new CombiningShapes());
    f.setSize(220, 220);
    f.center();
    f.setVisible(true);
}
private Shape mShapeOne, mShapeTwo;
private JComboBox mOptions; 


public CombiningShapes() {
   // Create the two shapes, a circle and a square.
   mShapeOne = new Ellipse2D.Double(40, 20, 80, 80);
   mShapeTwo = new Rectangle2D.Double(60, 40, 80, 80);
   setBackground(Color.white);
   setLayout(new BorderLayout());
  
   // Create a panel to hold the combo box.
   JPanel controls = new JPanel();

   // Create the combo box with the names of the area operators.
   mOptions = new JComboBox( new String[] { "outline", "add", "intersection",
        "subtract", "exclusive or" });

   // Repaint ourselves when the selection changes.
   mOptions.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent ie) {
       repaint();
      }
   });

   controls.add(mOptions);
   add(controls, BorderLayout.SOUTH);
}

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
   
    // Retrieve the selection option from the combo box.
    String option = (String)mOptions.getSelectedItem();
    if (option.equals("outline")) {

       // Just draw the outlines and return.
       g2.draw(mShapeOne);
       g2.draw(mShapeTwo);
       return;
    }

    // Create Areas from the shapes.
    Area areaOne = new Area(mShapeOne);
    Area areaTwo = new Area(mShapeTwo);

    // Combine the Areas according to the selected option.
    if (option.equals("add"))
         areaOne.add(areaTwo);
    else if (option.equals("intersection"))
        areaOne.intersect(areaTwo);
    else if (option.equals("subtract"))
        areaOne.subtract(areaTwo);
    else if (option.equals("exclusive or"))
        areaOne.exclusiveOr(areaTwo);

    // Fill the resulting Area.
    g2.setPaint(Color.orange);
    g2.fill(areaOne);
    // Draw the outline of the resulting Area.
    g2.setPaint(Color.black);
    g2.draw(areaOne);
  }

Hope this helps .

Friday, 25 May 2012

Draw Lines giving parabolic effect in Java

Today I am going to post a program in Java that will create an art using Java 2DGraphics and geometry. This code creates a curve like a parabola as shown in the screenshot below.
Here a set of lines are drawn with different points. The lines are drawn by joining of two points. These points are calculated very precisely over here so that whole thing gives a parabola like curve.It is very simple to create this design. Here is the code for you.

import java.awt.*;
import java.awt.geom.*;

public class Art extends Component {

     public static void main(String[] args) {
         try {
        
         ApplicationFrame f = new ApplicationFrame("ShowOff v1.0");
         f.setLayout(new BorderLayout());
         Art obj = new Art();
         f.add(obj, BorderLayout.CENTER);
         f.setSize(500,500);
         f.center();
         f.setResizable(false);
         f.setVisible(true);
      }catch (Exception e) {
           System.out.println(e);
           System.exit(0);
      }
  }
  
   private int mNumberOfLines = 25;
   private Color[] mColors = { Color.red, Color.green, Color.blue }; 

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Dimension d = getSize();
        for (int i = 0; i < mNumberOfLines; i++) {
           double ratio = (double)i / (double)mNumberOfLines;
           double ratio2 = (double)(mNumberOfLines-i-1) / (double)mNumberOfLines;
           Line2D line1 = new Line2D.Double(0, ratio * d.height,
                ratio * d.width, d.height);
           Line2D line2 = new Line2D.Double(ratio*d.width,0,
                d.width, ratio*d.height);
           Line2D line3 = new Line2D.Double(d.width,ratio*d.height,
                ratio2*d.width, d.height);
           Line2D line4 = new Line2D.Double(ratio2*d.width,0,
                0, ratio*d.height);
           g2.setPaint(mColors[i % mColors.length]);
           g2.draw(line1);
           g2.draw(line2);
           g2.draw(line3);
           g2.draw(line4);
         }
    }  
}

Note : This program won't compile unless you create a Java source file named ApplicationFrame that works as a Frame object by inheriting it. So please make the necessary changes. The actual Graphics code which has given the output as shown is written in the paint(Graphics) method.

Hope this helps.

Saturday, 19 May 2012

Singleton Class in Java

I hope many of you have heard of SINGLETON CLASS in Java. Even if you have not heard then also you must have experienced of such.Today I am going to post how to create a singleton class. Just as the word "single" means literally as "only one", similarly "singleton" here means "only one object". That means all classes that can have at most one object or only one object can be created of a class. You must have experienced this while installing a software. While an installation program is in progress you cannot run another installation program i.e. execute the same >EXE file while it is already in use. Here is the code for you to create a singleton class in Java -->

public final class MyClass{
    private static int count = 0;
// Optional 0
    private int n;
    public MyClass() throws Exception {
        this (0);
    }
    public MyClass(int n) throws Exception {
        if (count >= 1)
//exception object created and thrown
            throw new Exception("No more than one instance");
        count++;
        this.n = n;
    }
    public String toString() {
        return n + "";
    }
   
    public static void main(String[] args) throws Exception {
        System.out.println(new MyClass(10));
        // System.out.println(new MyClass());
       }
}

Uncomment the last line , then save it and then compile and run. It will give an output as shown below
But if it is commented then it will run absolutely fine.
Hope this helps :)

Friday, 11 May 2012

Create your own Clock in Java

Many programmers would like to create a Clock of his own. Today I am going to post a code on creating a digital cum analog clock using Java. This requires some mathematical calculations to find the position of the clock hands and numbers. This is done using java's Math class API. Here is the code for you ->


import  java.util.concurrent.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;


public class Clock extends JApplet {
    private int r;
    private boolean firsttime;
    private int x4, y4, xx4, yy4, x5, y5, xx5, yy5, x6, y6, xx6, yy6 ;
       
    private SimpleDateFormat formatter;  // Formats the date displayed
        private String todaydate,time;
        private Date currentDate;
        public void init() {
          r = 150;
          firsttime=true;
         MyThread mt = new MyThread(this);
         mt.start();
     }
   
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
       int theta, r1, r2, r3, r4,rr4,r5, rr5, r6, rr6, x1, x2, y1, y2, x3, y3 ;
       double radian;
       g2.translate(250, 250);
       if(firsttime) {
          g2.setColor(new Color(0, 0, 0));
          g2.setStroke(new BasicStroke(5));
          g2.drawOval(-r, -r, 2 * r, 2 * r);
          g2.fillOval(-r, -r, 2 * r, 2 * r);
          g2.setColor(new Color(255, 0, 0));
          g2.setStroke(new BasicStroke(2));
       
         for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            r1 = theta % 30 != 0 ? r - 5 : r - 10;
            x1 = (int)(r1 * Math.cos(radian));
            y1 = (int)(r1 * Math.sin(radian));
            r2 = r;
            x2 = (int)(r2 * Math.cos(radian));
            y2 = (int)(r2 * Math.sin(radian));
            g2.drawLine(x1, y1, x2, y2);
        }
        g2.translate(-5, 3);
        r3 = r - 19;
        g2.setColor(new Color(84,245,245));
        ///draw number on  clock face
        for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            if (theta % 30 == 0) {
                x3 = (int)(r3 * Math.cos(radian));
                y3 = (int)(r3 * Math.sin(radian));
                g2.drawString((theta == 270 ? 12 : (theta / 30 + 3) % 12) + "", x3, y3);
            }
        }
       
        firsttime=false;
       
        g2.translate(5, -3);   //after translation the center point is rebuild into ( 250,250 )
        }
        GregorianCalendar gc = new GregorianCalendar();
        currentDate = new Date();
        //date showing format
        formatter = new SimpleDateFormat ( "MMM dd EEE ", Locale.getDefault() );
        todaydate = formatter.format(currentDate);
        //time showing format
        formatter = new SimpleDateFormat ("hh:mm:ss ", Locale.getDefault());                      
        time=formatter.format(currentDate);
                           
        int hour = gc.get(Calendar.HOUR);
        int minute = gc.get(Calendar.MINUTE);
        int second = gc.get(Calendar.SECOND);
        int millisecond = gc.get(Calendar.MILLISECOND);
       
        //hour pointer
        radian =  (((30 * hour)+(minute/2))-90) * Math.PI / 180; 
        r4=3;
        rr4 = r-40;
        //cleanig process of previous hour pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(0, 0, 0));
        g2.drawLine(x4,y4,xx4,yy4);
        x4=  (int)(r4 * Math.cos(radian));
        y4 = (int)(r4 * Math.sin(radian));
        xx4 = (int)(rr4 * Math.cos(radian));
        yy4 = (int)(rr4 * Math.sin(radian));
       
        //minute pointer
        radian =  (((minute*6)+(second/12))-90) * Math.PI / 180; 
        r5=9;
        rr5 = r-35;
        //cleanig process of previous minute pointer
        g2.setStroke(new BasicStroke(2));       
        g2.drawLine(x5,y5,xx5,yy5);
       
        x5=  (int)(r5 * Math.cos(radian));
        y5 = (int)(r5 * Math.sin(radian));
        xx5 = (int)(rr5 * Math.cos(radian));
        yy5 = (int)(rr5 * Math.sin(radian));
       
        //second pointer
        radian =  ((( second*6)+(millisecond/200))-90) * Math.PI / 180; 
        r6=13;
        rr6 = r-30;
        //cleanig process of previous second pointer
        g2.setStroke(new BasicStroke(2));
        g2.drawLine(x6,y6,xx6,yy6);
        x6=  (int)(r6 * Math.cos(radian));
        y6 = (int)(r6 * Math.sin(radian));
        xx6 = (int)(rr6 * Math.cos(radian));
        yy6 = (int)(rr6 * Math.sin(radian));
               
        //time showing box       
        g2.setColor(new Color(255,255,255));
        g2.fillRect(-40,50,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(-40,50,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(time+(gc.get(Calendar.AM_PM)==1?"PM":"AM"),-35,65);
       
        //date showing box
        g2.setColor(new Color(255,255,255));
        g2.fillRect(40,-15,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(40,-15,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(todaydate,45,0);
       
        //draw hour pointer
        g2.setColor(new Color(4,255,250));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-3,-3,6,6);
        g2.drawLine(x4,y4,xx4,yy4);
       
        //draw minute pointer
        g2.setColor(new Color(255,0,0));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-9,-9,18,18);
        g2.drawLine(x5,y5,xx5,yy5);
       
        //draw second pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(11, 196, 6));
        g2.drawOval(-13,-13,26,26);
        g2.drawLine(x6,y6,xx6,yy6);
             
    }
          public static void main(String s[]) throws Exception{
         final JFrame f = new JFrame("Clock");
         final JApplet applet = new Clock();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setBackground(new Color(253,206,243));
          f.setSize(500,500);
          f.setVisible(true);
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            applet.repaint();   
            f.setLayout(new FlowLayout());   
            }
        });
          TimeUnit.SECONDS.sleep(0);
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
         applet.setSize(500,500);
         f.add(applet);
         applet.init();   
       }
     });
       } 
}


class MyThread extends  Thread {
    private Clock c;
    public MyThread(Clock c) {
        this.c = c;
    }
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                c.repaint();
            }
            catch (Exception e) {
            }
       }
    }   

You can also download source from below link->
Download Java source file from Mediafire
Hope this helps .