Friday, May 7, 2010

JAVA : Calendar

Creating a Graphical Calendar in Java:-





Graphical Calender


!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!!

Graphical Calendar is a purely JAVA based application.This Java application provides you a fully function Graphical Calendar. Java does not provide a inbuilt Graphical calendar but it has a Calendar class in java.utill package.Java's Calendar class provide you a set of methods for getting date, time and other date-time arithmetics.

import java.util.Calendar;

public class Cal{

  public static void main(String[] args){
     Calendar calendar = Calendar.getInstance ();
  }

}


GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world. A Calendar object can be initialized by GregorianCalendar class.

import java.util.Calendar;

public class Cal{

  public static void main(String[] args){
     Calendar now = GregorianCalendar.getInstance();
  }

}

This Graphical Calendar allows you to choose a year, a month and a day. On loading application uses the current date as of your system. This Graphical Calendar can also be used as a date picker in any of Java application if needed. For example in a Railway reservation system this Calendar can be used as a date picker.

Download Files Here:


Coding for making Grahical Calendar :-


Celendar.java:- In Celendar.java the coding for setting the look and feel and adding the Days panel in the frame is done.


import java.awt.*;
import javax.swing.*;
import javax.swing.UIManager.*;

public class Celendar extends JFrame{

private JPanel p;

Celendar(){
super("Calendar");

try {
   for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
   
    if ("Nimbus".equals(info.getName())) {
           UIManager.setLookAndFeel(info.getClassName());
       
           break;
       }
       else{
                                               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
       }
   }
} catch (Exception e) {

}
setLayout(new GridLayout(1,1));
setSize(322,223);
setResizable(false);
Days d= new Days();

add(d);
}


public static void main(String aggsp[]){

Celendar c = new Celendar();
c.setVisible(true);
c.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}



Days.java:- In this Days.java file all the coding of basic calendar is done.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.UIManager;
import java.util.*;

public class Days extends JPanel {

//lables use for showing weekday names
private JLabel sun;
private JLabel mon;
private JLabel tue;
private JLabel wed;
private JLabel thu;
private JLabel fri;
private JLabel sat;


        //need to images blackArrowUp.gif and upArrowUp.gif  to put on up and down button 
private Icon pic[]= {new ImageIcon(getClass().getResource("blackArrowUp.gif")),new ImageIcon(getClass().getResource("blackArrowDown.gif"))};

private JPanel mainpanel;   //for add days and weekday
private JPanel p[]= new JPanel[42]; //Array of Panels for Adding Days Buttons
private JButton b[]= new JButton[31]; //Array of 31 Buttons For 31 Days


//for year , month and date (all will be added to Pannel )


private JPanel mainp; //main Panel on which date , year and month will add
private JTextField date; //for showing date in text fields
public JComboBox month; //for months
public JTextField year; //for year
private JButton sb[]= new JButton[2]; // for increasing year by 1 on every click

//string array has name of months for adding to combobox

private String strmon[]= {"January","Febuary","March","April","May","June","July","Augest","September","October","November","December"};

//Constructor Start
Days(){


setLayout(null); //setting layout
setSize(350,228);
setVisible(true);



//first Frame Build

mainp = new JPanel();
mainp.setLayout(null);
mainp.setSize(325,31);
mainp.setLocation(1,0);



date = new JTextField(); //date textField will strore the date
date.setSize(100,30);
date.setLocation(5,0);
date.setBackground(Color.WHITE);
date.setFont(new Font("Arial",Font.PLAIN,14));
date.setEditable(false);

month = new JComboBox(strmon); //month combo box will have all months
month.setSize(90,30);
month.setLocation(110,0);


year = new JTextField("2008"); //year will have year part of date
year.setSize(70,30);
year.setLocation(205,0);
year.setBackground(Color.WHITE);
year.setEditable(false);

sb[0] = new JButton(""); //sb scroll bar increments the year by 1
sb[0].setSize(30,15);
sb[0].setLocation(275,0);
sb[0].setIcon(pic[0]);

sb[1] = new JButton(""); //sb scroll bar increments the year by 1
sb[1].setSize(30,15);
sb[1].setLocation(275,16);
sb[1].setIcon(pic[1]);

mainp.add(date);
mainp.add(month);
mainp.add(year);
mainp.add(sb[0]);
mainp.add(sb[1]);
add(mainp);


//Days Panel

mainpanel = new JPanel();
mainpanel.setLayout(new GridLayout(7,7,1,1));
mainpanel.setSize(315,160);
mainpanel.setLocation(1,31);

sun = new JLabel("Sun");
sun.setForeground(Color.RED);
mon = new JLabel("Mon");
tue = new JLabel("Tue");
wed = new JLabel("Wed");
thu = new JLabel("Thu");
fri = new JLabel("Fri");
sat = new JLabel("Sat");

//add labels to panel
mainpanel.add(sun);
mainpanel.add(mon);
mainpanel.add(tue);
mainpanel.add(wed);
mainpanel.add(thu);
mainpanel.add(fri);
mainpanel.add(sat);

//Initializing memory to Jpanels and add it to mainpanel
for (int x=0;x<42;x++){
p[x]= new JPanel();
p[x].setLayout(new GridLayout(1,1));
p[x].setBackground(Color.WHITE);
mainpanel.add(p[x]);
validate();
}

final HandlerClass handler= new HandlerClass(); // object of handlerclass

for (int i=0;i<31;i++){ //only Initializing memory to buttons not adding them
b[i]= new JButton();
b[i].addActionListener(handler);
b[i].setFont(new Font("Times New Roman",Font.PLAIN,11));
b[i].setText(Integer.toString(i+1));

}


final Calendar now = GregorianCalendar.getInstance(); //create a Calendar object
year.setText(Integer.toString(now.get(Calendar.YEAR))); //get year and month from Calendar object
month.setSelectedIndex(now.get(Calendar.MONTH)); //add values to year and month

validate();

// DAY_OF_WEEK GIVES THE DAY OF THE FROM WIHCH THE MONTH STARTS
int ye=Integer.parseInt(year.getText());
Calendar cal = new GregorianCalendar(ye, month.getSelectedIndex(), 1);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

for (int i=0;i             //loop running according to the number of days  
p[dayOfWeek-1].add(b[i]);               //adding the days button on pannels according to the dayof week
dayOfWeek++;
}

int bd=now.get(Calendar.DATE); //getting the current date
b[bd-1].setEnabled(false); // sets the current date button enabled false


add(mainpanel); // add main pannel to

validate();

month.addItemListener(
new ItemListener(){

public void itemStateChanged(ItemEvent event){
if (event.getStateChange()==ItemEvent.SELECTED){
mainpanel.removeAll();
validate();

mainpanel.add(sun);
mainpanel.add(mon);
mainpanel.add(tue);
mainpanel.add(wed);
mainpanel.add(thu);
mainpanel.add(fri);
mainpanel.add(sat);

for (int x=0;x<42;x++){

p[x].removeAll();
mainpanel.add(p[x]);
validate();
}


int ye=Integer.parseInt(year.getText());
Calendar cal = new GregorianCalendar(ye, month.getSelectedIndex(), 1);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

for (int i=0;i

p[dayOfWeek-1].add(b[i]);
dayOfWeek++;
validate();
}
validate();
}
mainp.validate();
validate();

date.setText(Integer.toString(handler.db +1).concat(" / ").concat(Integer.toString(month.getSelectedIndex() + 1)).concat(" / ").concat(year.getText()));
}
}
);


sb[0].addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
int y = Integer.parseInt(year.getText());
y++;
year.setText(Integer.toString(y));



mainpanel.removeAll();
validate();

mainpanel.add(sun);
mainpanel.add(mon);
mainpanel.add(tue);
mainpanel.add(wed);
mainpanel.add(thu);
mainpanel.add(fri);
mainpanel.add(sat);

for (int x=0;x<42;x++){


p[x].removeAll();
mainpanel.add(p[x]);
validate();
}


int ye=Integer.parseInt(year.getText());
Calendar cal = new GregorianCalendar(ye, month.getSelectedIndex(), 1);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

for (int i=0;i

p[dayOfWeek-1].add(b[i]);
dayOfWeek++;
validate();
}


validate();
//sets the date on Click of year Button
date.setText(Integer.toString(handler.db +1).concat(" / ").concat(Integer.toString(month.getSelectedIndex() + 1)).concat(" / ").concat(year.getText()));

}

}
);



sb[1].addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
int y = Integer.parseInt(year.getText());
y--;
year.setText(Integer.toString(y));



mainpanel.removeAll();
validate();

mainpanel.add(sun);
mainpanel.add(mon);
mainpanel.add(tue);
mainpanel.add(wed);
mainpanel.add(thu);
mainpanel.add(fri);
mainpanel.add(sat);

for (int x=0;x<42;x++){


p[x].removeAll();
mainpanel.add(p[x]);
validate();
}


int ye=Integer.parseInt(year.getText());
Calendar cal = new GregorianCalendar(ye, month.getSelectedIndex(), 1);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

for (int i=0;i

p[dayOfWeek-1].add(b[i]);
dayOfWeek++;
validate();
}


validate();
//sets the date on Click of year Button
date.setText(Integer.toString(handler.db +1).concat(" / ").concat(Integer.toString(month.getSelectedIndex() + 1)).concat(" / ").concat(year.getText()));

}

}
);



//sets the date on form load
date.setText(Integer.toString(handler.db +1).concat(" / ").concat(Integer.toString(month.getSelectedIndex() + 1)).concat(" / ").concat(year.getText()));
}





//returns no. of days in a week
public int getDaysNo(){
int no = 31;
if (month.getSelectedIndex()==1){
no=28;
if (Integer.parseInt(year.getText())%4==0){
no=29;

}
month.validate();
}

if (month.getSelectedIndex()==3 || month.getSelectedIndex()==5 || month.getSelectedIndex()==8 || month.getSelectedIndex()==10)
{
no=30;
}
return no;

}


// handler class set which date is selected

class HandlerClass implements ActionListener{


Calendar now = Calendar.getInstance();
public int db=(now.get(Calendar.DATE))-1;

public void actionPerformed(ActionEvent e){

for (int k=0;k<31;k++){

if (e.getSource()==b[k])
{
b[k].setEnabled(false);
validate();
db=k;

}
else{
b[k].setEnabled(true);
validate();
}
month.validate();

}


date.setText(Integer.toString(db +1).concat(" / ").concat(Integer.toString(month.getSelectedIndex()+1)).concat(" / ").concat(year.getText()));
}


}

}


JAVA : Analog Clock

JAVA Analog Clock 





!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!!
Java code spot has come up with a simple analog clock written in Java. It comes as an applet, as well with the source code.  


For making the analog clock we have some mathematics calculations to find out the points  where the clock's parts like hands, digits will get paint. The Java program calculates the point positions on the bases of angle and the time. For example every second the clock's hand will move six degrees. In radian the 6 degrees is equal to 0.1047. So if we want the minutes hand to be on 15 minutes than we can can calculate that it should be placed on the angle of  0.1047*15 radians.


Here is the code to calculate points for painting clock:






int h=40;  //radius of clock



Calendar now = Calendar.getInstance(); //creating a Calendar variable for getting current time


  x=100;         
    y=100;
    theta=-0.1047;
    theta=theta*now.get(Calendar.SECOND);
   int  p=  (int) (Math.sin(theta) * h);
   int b=  (int) (Math.cos(theta) * h);
    x=x-p;
    y=y-b;

This Java Analog Clock can be dragged with mouse form one location to another.


Code for Creating Clock:-



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class Clock extends Frame implements MouseMotionListener{
int xmou=200; //set the center of circle
int ymou=200; //set the center of circle

double theta=-0.1047; //theta for second's hand
int x=xmou; //x position of Second's hand
int y=ymou; //y position of second's hand
int p,b; //perpendicular and base of Second's hand

int h; //hypotenous(heigth) of clock's hand


double the= -0.1047; //theta for creating outer circle

double thetamin=-0.1047;        //theta for minutes hand
int xm=xmou; //x position of minute's hand
int ym=ymou; //y position of minute's hand
int pmin,bmin; //perpendicular and base of Minute's hand


double thetah=-0.1047;         //theta for hour hand
int xh=xmou; //y position of hour's hand
int yh=ymou; //y position of hour's hand
int ph,bh; //perpendicular and base of hour's hand


double thetan=-0.0;          //theta for numbers of clock
int xn=xmou; //x position of Clock numbers
int yn=ymou; //y position of Clock numbers
int pn,bn; //perpendicular and base of clock numbers
int num=0; //for writing the numbers


//constructor

Clock(){
super();
setSize(500,500);
setBackground(Color.PINK);
setVisible(true);
addMouseMotionListener(this);
}


//method of implemented  mouse interface
public void mouseMoved(MouseEvent me){

}

public void mouseDragged(MouseEvent me){
xmou=me.getX(); //changing the clock position on mouse drag
ymou=me.getY(); //changing the clock position on mouse drag

}


//method to paint clock
public void paint(Graphics g){
      
           //for writing numbers in clock and outer circle

for(int p=0;p<60;p++){
  
        int xocir=xmou;      //x position of outer circle
     int yocir=ymou;      //y position of outer circle
     int pocir,bocir;     //perpendicular and base of outer circle

            pocir=  (int) (Math.sin(the) * (h+23));
            bocir=  (int) (Math.cos(the) * (h+23));
            xocir=xocir-pocir;
            yocir=yocir-bocir;
            the=the - 0.1047;

                 g.setColor(Color.BLUE);
         g.drawLine(xocir+5,yocir+5,xocir,yocir);
                g.setColor(Color.BLACK);
if(p%5==0 ){
num++;
if(num>12){
 num=1;
}

xn=xmou;
     yn=ymou;

if(thetan<=-6.28318531 ){
thetan=0.0;

}
thetan=thetan-0.523598776 ;
     pn=  (int) (Math.sin(thetan) * (h+10));
     bn=  (int) (Math.cos(thetan) * (h+10));
     xn=xn-pn;
     yn=yn-bn;
g.drawString(""+num,xn-3,yn+5);

   }      

     }
  
     //for drawing Clock hands

     g.setColor(Color.BLACK);
  
     g.drawLine(xmou,ymou,xm,ym); //drawing minute's hand
     g.drawLine(xmou,ymou,xh,yh); //drawing hour's hand
  
     g.setColor(Color.RED);
     g.drawLine(xmou,ymou,x,y); //drawing second's hand
      
    }


 public void newpoint(){

    Calendar now = Calendar.getInstance(); //creating a Calendar variable for getting current time

    //for second hand

    x=xmou;
    y=ymou;
    theta=-0.1047;
    theta=theta*now.get(Calendar.SECOND);
    p=  (int) (Math.sin(theta) * h);
    b=  (int) (Math.cos(theta) * h);
    x=x-p;
    y=y-b;
    //theta=theta - 0.1047;

  //for minutes hand

    xm=xmou;
    ym=ymou;

    thetamin=-0.1047;
    thetamin=thetamin*now.get(Calendar.MINUTE);
    pmin=  (int) (Math.sin(thetamin) * (h-6));
    bmin=  (int) (Math.cos(thetamin) * (h-6));
    xm=xm-pmin;
    ym=ym-bmin;

    //for hour's hand

    xh=xmou;
    yh=ymou;
    thetah=-0.1047;
    thetah=thetah*now.get(Calendar.HOUR)*5;


   if (now.get(Calendar.MINUTE)>=12 && now.get(Calendar.MINUTE)<24){
  thetah=thetah-0.1047;


   }
   else if(now.get(Calendar.MINUTE)>=24 && now.get(Calendar.MINUTE)<36){
  thetah=thetah-(2*0.1047);


   }
   else if(now.get(Calendar.MINUTE)>=36 && now.get(Calendar.MINUTE)<48){
  thetah=thetah-(3*0.1047);


   }
   else if(now.get(Calendar.MINUTE)>=48 && now.get(Calendar.MINUTE)<60){
  thetah=thetah-(4*0.1047);


   }


    ph=  (int) (Math.sin(thetah) * (h-15));
    bh=  (int) (Math.cos(thetah) * (h-15));
    xh=xh-ph;
    yh=yh-bh;




 }
  

   public static void main(String[] args) {
    
        Clock m=new Clock();
        m.h=60;
    
         while(true){
  
         m.newpoint();
         m.repaint();
         try{
     Thread.sleep(6);
     }catch(Exception e){
    
     }    
      }
    }

}

JAVA : Scroll Bar Animation

Creating a Frame in which a number of Scrollbar (for example 20 Scrollbar) are doing animations.




 Code For Creating Scrollbar animation:-



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Scrollbar extends JFrame implements Runnable{
JScrollBar sb[]= new JScrollBar[20];            //declaring a array of 20 Scroll Bars
int i=1;                                                      //variable to know how many scroll bar will change in there value(used in animation)
boolean b=true;

Scrollbar(){
super();
setLayout(new GridLayout(1,1));                    //setting the layout

for(int a=0;a<20;a++){                                //loop for initializing memory to scrollbars
sb[a]= new JScrollBar();
sb[a].setMaximum(5000);                         //setting maximum value of scrollbar
sb[a].setVisibleAmount(2000);                 //setting visible amount of sliding bar
add(sb[a]); //adding scrollbar to frame
}

}


public void animation(){
try{

for(int n=0;n<=i;n++){
                        //this will run for increment the scrollbar visible amount
if((sb[n].getVisibleAmount()+22)<4000 && b==true)
{
//setting visible amount of sliding bar 
sb[n].setVisibleAmount(sb[n].getVisibleAmount()+n+1);

}

else{
b=false;         //boolean to decide which if condition will run
}



//this will run for decrement the scrollbar visible amount
if( (sb[n].getVisibleAmount()-22)>1000 && b==false){

 //setting visible amount of sliding bar 

sb[n].setVisibleAmount(sb[n].getVisibleAmount()-n-1);
}
else{
b=true;                     //boolean to decide which if condition will run
}
}

if (i<19){
i++;          //increment variable i (every time loops runs i incremented by 1 which increases the
                        //number of scroll bar changing there visible amount )
}
else{
i=0;          //if i becomes greater than number of scrollbar then setting i=0
}

}
catch(Exception e){
System.out.println("error" +e);
}
}

//function of implemented interface runnable

public void run(){
 while(true){                             //running the animation in infinite loop
animation();
try{
Thread.sleep(2);
}
catch(Exception e){
}
}

}


public static void main(String a[]){
Scrollbar s= new Scrollbar();
s.setVisible(true);
s.setDefaultCloseOperation(EXIT_ON_CLOSE);
s.setSize(370,700);
Thread t = new Thread(s);                 //creating thread
t.start();
}
}



Working of Program :-


Making a Thread:-
Thread is a single sequential flow of control within a program. Programmer may use java thread mechanism to execute multiple tasks at the same time. 
Here, Thread is use to run a process(animation method) in infinite loop and thread sleeps for 2 milliseconds every time time loop run again.


Animation method:-
Animation method  contains a for loop in which there is two if conditions, one for incrementing the visible amount of sliding bar and another is for decrementing the visible amount of sliding bar.
Every time the loop runs the the visible amount of the sliding bar gets increment till the value reaches the 4000 and then the decrement of visible amount starts until the value reaches 1000 and the same process goes on.