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

   add(controls, BorderLayout.SOUTH);

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

       // Just draw the outlines and 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"))
    else if (option.equals("intersection"))
    else if (option.equals("subtract"))
    else if (option.equals("exclusive or"))

    // Fill the resulting Area.
    // Draw the outline of the resulting Area.

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);
      }catch (Exception e) {
   private int mNumberOfLines = 25;
   private Color[] mColors = {,, }; 

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

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");
        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;
         MyThread mt = new MyThread(this);
    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);
        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());                      
        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; 
        rr4 = r-40;
        //cleanig process of previous hour pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(0, 0, 0));
        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; 
        rr5 = r-35;
        //cleanig process of previous minute pointer
        g2.setStroke(new BasicStroke(2));       
        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; 
        rr6 = r-30;
        //cleanig process of previous second pointer
        g2.setStroke(new BasicStroke(2));
        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.setColor(new Color(207,158,248));
        g2.setColor(new Color(0,0,0));
        //date showing box
        g2.setColor(new Color(255,255,255));
        g2.setColor(new Color(207,158,248));
        g2.setColor(new Color(0,0,0));
        //draw hour pointer
        g2.setColor(new Color(4,255,250));
        g2.setStroke(new BasicStroke(2));
        //draw minute pointer
        g2.setColor(new Color(255,0,0));
        g2.setStroke(new BasicStroke(2));
        //draw second pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(11, 196, 6));
          public static void main(String s[]) throws Exception{
         final JFrame f = new JFrame("Clock");
         final JApplet applet = new Clock();
          f.setBackground(new Color(253,206,243));
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            f.setLayout(new FlowLayout());   
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {

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

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