Wednesday, December 15, 2010

JAVA : Font Formatter

JAVA Font Formatter

Font Formatter is a Java application that allows user to manipulate font in different ways like font type, font size, and font style. This Font Formatter Java application shows the use of font utility that can be used in many other programs.


!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!!
Instruction:-
1.) Select the type of font from the options in combo box.
2.) Select the size of font form the second combo box.
3.) Check or uncheck the Bold or Italic check box to change the style of font.
4.) Press Quit Button to Quit.

Available fonts:
To get the available fonts list in Java a toolkit object is used. A toolkit object contains the list of the available fonts which can be fetched using a in build method.



                String[ ] fontList;
fontList = Toolkit.getDefaultToolkit().getFontList();


In this program a createFontChoice() function is written for making a combo box list of available fonts.



    private void createFontChoice() {

fontChoice.addItemListener(this);
String[] fontList;
fontList = Toolkit.getDefaultToolkit().getFontList();
for(int i=0; i<fontlist.length; i++){
fontChoice.addItem(fontList[i]);
 }
              fontName = fontList[0];
}

Download Files Here:


Wednesday, December 1, 2010

JAVA : Paint Application

JAVA Paint Application

Java Paint application is a simple applet implementation of MS paint like application implemented in Java written by Java Code Spot which allows user to draw different shapes and basic drawing. It has the basic drawing tools such as point, line, rectangles, round rectangles and circles and color manipulation options, other than that it has eraser tool. Paint application is a good example of how to use java's graphics libraries.

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

Instruction:
1)Select the drawing tool from the combo box.
2)Check draw or fill option to choose how to draw.
3)Check eraser option for using eraser tool.
4)Choose color of drawing from color combo box.
5)Press 'z' for undo.

Download Files Here:


Friday, September 24, 2010

JAVA : Music Player

JAVA Music Player

Java Code Spot has come up with a small Music Player Java application that plays wave sound clips. Playing sounds clips in java can be done using the "javax.sound" pakages.

Java Sound supports the following audio file formats: AIFF, AU and WAV.


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

Instruction:
1)play button will paly the selected sound clip once.
2)Loop Button will play the selected sound clip continuesly.
3)Stop Button will stop the playing sound.
Note: It takes some time to load sound clip before playing according to your internet speed.

JAVA AudioInputStream:
For playing a sound file in Java application we need to create a object of AudioInputStream. AudioInputStream is input stream for audio files like DataInputStream are for data files. An audio input stream is an input stream with a specified audio format and length.

public void selectFile(){

   try {

      URL u = new URL(getCodeBase()+""+playlist.getSelectedItem());
           AudioInputStream  ai = AudioSystem.getAudioInputStream(u);

      } catch (Exception e) {
           e.printStackTrace();
     }
}



JAVA Clip Interface:
As AudioInputStream is just an input stream, we cannot directly play them. For playing these java AudioInputStream, Java has a interface Clip in Javax.sound.sampled package.
The Clip interface represents a special kind of data line whose audio data can be loaded prior to playback, instead of being streamed in real time.


             Clip c =  AudioSystem.getClip();
          c.open(ai);
          c.start();
          c.loop(Clip.LOOP_CONTINUOUSLY);
          c.stop();
          c.close();
        
The Clip interface has some functions which can be use to paly audio files.

open() : Java's Clip interface has a open function that takes AudioInputStream as parameter and opens the clip with the format and audio data present in the provided audio input stream. Opening a clip means that it should acquire any required system resources and become operational.

start() : Java's Clip interface has a start function that starts playing the AudioInputStream which is currently open.

loop() : Java's Clip interface has a loop function that continously plays the AudioInputStream which is currently open.

stop() : Java's Clip interface has a stop function that stops the playing AudioInputStream.

close() : Java's Clip interface has a close function that Closes the line and releasese any system resources in use by the line.

Download Files Here:

Tuesday, August 31, 2010

JAVA : Sorting Animations

JAVA Sorting Animations:

Sorting animations is a Java application that shows how a sorting alogrithm works by graphical animations. In this Java application working of four sorting alogrithm are shown through animations. 




!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!!
Selection Sort:

Selection Sort is a very simple algorithm but it is inefficent on large lists.
The Selection algorithm works as follows:
  1. Find the minimum value in the list
  2. Swap it with the value in the first position
  3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)
  JAVA Code for Selection Sort Algorithm
//Selection sort algorithm method 
  public List sort(List a) throws Exception {
int max,min,pos=0;
     boolean swapped=false;
     for(int i=0; i < a.size(); i++){
              swapped=false;
              max=min=a.get(i);
              for(int j=i+1; j < a.size() ; j++){
                                     if(min>a.get(j)){
                                                 min=a.get(j);
  pos=j;
 swapped=true;
                                     }
               }

  if(swapped){
                    a.set(i, min);
                    a.set(pos, max);    
              }
      }
return a;
}//end of sort method

Selection sort algorithm performance:-
  • Worst case performance -
  • Best case performance -
  • Average case performance-
Bubble Sort:

Bubble sort is a sorting algorithm that works by repeatedly traversing through the list and compares the current element with the next one and swap them if they appears in wrong order. Traversing through the list is repeated until no swaps are needed. To known that the list is sorted we need to have one traversing through the list with no swap that means we need to traverse the list one more time even if the list is already sorted.


  JAVA Code for Bubble Sort Algorithm
 //bubble sort algorithm method
 public List sort(List a) throws Exception {
      boolean swapped =false;
for (int i = a.size()-1; i >= 0; i--) {
                  swapped = false;
                 for (int j = 0; j < i; j++) {

    if (a.get(j) > a.get(j+1)) {
                                    int T = a.get(j);
                                    a.set(j, a.get(j+1));
                                     a.set(j+1, T);
   swapped = true;
}
                    }
                 if(!swapped){
                           break;
}
}
return a;
}//end of sort method


Bubble Sort Algorithm Performance:-
  • Worst case performance -
  • Best case performance - n
  • Average case performance-
Insertion sort:

Insertion sort is good only for sorting small arrays (usually less than 100 items). In fact, the smaller the array, the faster insertion sort is compared to any other more advance  sorting algorithm such as Qucik sort.

  JAVA Code for Insertion Sort Algorithm
//insertion sort algorithm method 
 public List sort(List a) throws Exception {
       boolean swapped =false;
       int i, j, temp;
        for (i = 1; i < a.size(); i++) {
                temp = a.get(i);
                j = i;
              while (j > 0 && a.get(j - 1) > temp) {
                    a.set(j, a.get(j - 1));
                     j--;
               }
             a.set(j, temp);
       }
     
return a;
}//end of sort method



Insertion Sort Algorithm Performance:-
  • Worst case performance -
  • Best case performance - n
  • Average case performance-
Quick Sort:

Quick sort is a faster in practice and more advance sorting alogrithm as compare to some other simple algorithm such as Selection sort or Bubble sort.
  JAVA Code for Quick Sort Algorithm
//Quick sort algorithm method 
 public List sort(List a, int left, int right) throws Exception {
int mid,tmp,i,j;
 
  mid = a.get((left + right)/2);
  
  do {
       while(a.get(i) < mid){
          i++;
          
       }
      while(mid < a.get(j)){
          j--;
          
      }
      if (i <= j) {
          tmp = a.get(i);
          a.set(i, a.get(j));
          a.set(j, tmp);
          i++;
          j--;
      }
  } while (i <= j);
  if (left < j){
  sort(a,left,j);
  }
  if (i < right){ 
  sort(a,i,right);
  }
 
     return a;
}//end of sort method


Quick Sort Algorithm Performance:-
  • Worst case performance   -
  • Best case performance -       nlogn
  • Average case performance- nlogn

Download Files Here:


Sunday, August 22, 2010

JAVA : Typing Test

Typing Test 
Manoj Tiwari


How fast can you type? Find out with Typing Test JAVA application.
Select a time and text to type. After completing the test, you will see your typing speed, accuracy and net speed.




!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!
Typing Test  is a Java program that tests your typing speed. You get a number of tests to choose from. Typing Test program counts the number of total words and worng words and on basis of that gives result.


Instructions

1. Choose a Test from List. 
2. Choose the time for test.
3. Click "Start" Button.
4. Typing test will appear. Time will start when you start typing.
5. A mistake done once can not be corrected (i.e. you cannot correct the Word once you hit the space bar).
6. Keep on typing until the time passes or hit the Finish Button.
7. Your Result will be displayed.

Scoring

Typing Test program will count the number of the correctly typed words and wrong typed word. If you mistype a word, it will be highlighted. Result has three parts 
1. Gross speed(total number of words typed divide by total time of test) 
2. Accuracy (Percentage of Correctly typed word out of  total number of words typed )
3. Net Speed (number of words correctly typed divide by total time of test)


Files

TestPage.java and TestPageapp.java:-
TestPage.java is the main class for running Typing Test as System application and TestPageapp.java is the main class for running Typing Test as Web pages(Applet).
These classes have the code for Making a window, setting Look and Feel and have two functions startTest() which runs when test starts and endTest() which runs when test end.

MainPage.java:-
MainPage.java is the first frame that displays  when application starts.This page contains a List of Test to choose form and a Combo Box to choose time for test.

TypingTime.java:-
TypingTime.java is file that has code for running time test starts. It has three function getTestTime() that gives the total time taken for test and getMin() that gives the minutes of test's time left and getSec() that gives the seconds of test's time left.

FileTextPage.java:-
FileTestPage.java is the class that has most of the coding. It adds two JTextArea on the frame in which one contains the text from the file and in other JTextArea user will type that text.
This file has the following functions in coding:
fileInput():-  Load text from file to JTextArea.
underliine():- Gets and the next word to be typed and highlight that word in TextArea.
check():- Checks weather the word user type matches with the word which has to be typed.
backSpace():- Allows user to only correct currently typing word(cannot go beyond the space).
result():- Calculate and Show Result.

Download Files Here:



Monday, August 16, 2010

JAVA : Flickering Problem In Paint Method

Remove Flickering Problem


 Flickering is a big problem while drawing something on screen in Java. Flickering normally occurs when drawing images one after another. Though flickering is a big problem people might think that it could be very complicated to avoid or remove it completely, but it is quite easy to that. By making some simple changes in your code you can completely remove flickering in your animations.
No Flickering                                                     Flickering 


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

What causes flickering in Java? 
Before flickering problem can be solved, we should know what causes it? As we know the paint() method in Java first clears the screen and then paints a new frame on the window. So there are two operations takes place when we can the paint() or repaint() method. So some times screen gets updated between the clearing of window and painting of new frame and in that moment of time we can see the cleared window and that makes it appear to be flicker.

Remove Flickering using Double Buffering:
As now we know that the flickering occurs because of refreshing of screen between the clearing of window and painting of new frame, so the solution is to paint the window in such a way that screen doesn't get refreshed before window get completely painted.
This can be done using the Double Buffering. To implement Double Buffering a BufferedImage class. A BufferedImage object is like an Image object except it has some method that makes it easier to work with.

Code in which flickering problem occur

public void run(){
            try{
                Thread.sleep(50);
            }
             catch(Exception e){ }
            repaint();
}
public void paint(Graphics g){
         animation(g);          //this function performs all animation
}


Code for Declaration of Buffered Image object

 
BufferedImage  bf = new BufferedImage( this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);

Code for Remove flickering in paint method by using Buffered Image
public void run(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
            paint(this.getGraphics());
            }
      }
public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
      }

This is how a Buffered Image object is use to prevent the flicker problem. When calling the animation() method a graphics object is extracted form Buffered Image. This Buffered Image graphics object is same as the normal(window) graphics object except this graphics object contains information about the Buffered Image instead of the actual window. That means the animation method paints the new frame on the Buffered Image instead of the actual window. So far the window still holds the old frame and the Buffered Image holds the new frame. Than a call is made to the drawImage() method of graphics object of the window. So now in only one operation the whole content of window is replace by  the content of Buffered Image. This is known as an atomic operation and the screen can not get refreshed while the window is partially painted. This is how the flickering problem can be solved and this code can be use for any type of application.

Now to understand why this code does not use repaint() method we need to understand the repaint() method.

Working of repaint() method:
Some people might think that repaint() method calls to the paint() method, eventually it does but it is not the whole story though. A repaint() method actually calls the update() method and the default update() method then calls to the paint() method. If you Java code did not override update(), the default implementation of update() clears the component's background and simply calls paint().
So if we want to use repaint() method we have to override update() method to avoid flickering.

public void run(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
              repaint();
            }
      }

public void update(Graphics g){
       paint(g);
}

public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
}

Download Files Here:


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


}

}