Java Swing Topics

Document Sample
Java Swing Topics Powered By Docstoc
					                                        Java Swing

Java Swing is a GUI toolkit for Java. Swing is one part of the Java Foundation Classes (JFC).
Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes,
and tables.

Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit.
Since they are written in pure Java, they run the same on all platforms, unlike the AWT which is tied to
the underlying platform's windowing system. Swing supports pluggable look and feel not by using the
native platform's facilities, but by roughly emulating them. This means you can get any supported look
and feel on any platform. The disadvantage of lightweight components is possibly slower execution. The
advantage is uniform behavior on all platforms.

History

The Internet Foundation Classes (IFC) were a graphics library for Java originally developed by
Netscape Communications Corporation and first released on Dec 16, 1996.

On April 2, 1996, Sun Microsystems and Netscape Communications Corporation announced
their intention to combine IFC with other technologies to form the Java Foundation Classes. In
addition to the components originally provided by IFC, Swing introduced a mechanism that
allowed the look and feel of every component in an application to be altered without making
substantial changes to the application code. The introduction of support for a pluggable look and
feel allowed Swing components to emulate the appearance of native components while still
retaining the benefits of platform independence. This feature also makes it easy to have an
individual application's appearance look very different from other native programs.

Originally distributed as a separately downloadable library, Swing has been included as part of the Java
Standard Edition since release 1.2. The Swing classes are contained in the javax.swing package hierarchy.

Architecture

The Swing library makes heavy use of the Model/View/Controller software design pattern, which
attempts to separate the data being viewed from the method by which it is viewed. Because of this,
most Swing components have associated models (typically as interfaces), and the programmer can use
various default implementations or provide their own. For example, the JTable has a model called
TableModel that describes an interface for how a table would access tabular data. A default
implementation of this operates on a two-dimensional array.

Swing favors relative layouts (which specify the positional relationships between components), as
opposed to absolute layouts (which specify the exact location and size of components). The motivation
for this is to allow Swing applications to work and appear visually correct regardless of the underlying
systems colors, fonts, language, sizes or I/O devices. This can make screen design somewhat difficult and
numerous tools have been developed to allow visual designing of screens.
Swing also uses a publish subscribe event model (as does AWT), where listeners subscribe to events that
are fired by the application (such as pressing a button, entering text or clicking a checkbox). The model
classes typically include, as part of their interface, methods for attaching listeners (this is the publish
aspect of the event model).

The frequent use of loose coupling within the framework makes Swing programming somewhat
different from higher-level GUI design languages and 4GLs. This is a contributing factor to Swing having
such a steep learning curve.

Look and feel

Swing allows one to specialize the look and feel of widgets, by modifying the default (via runtime
parameters), deriving from an existing one, by creating one from scratch, or, beginning with J2SE 5.0, by
using the skinnable Synth Look and Feel, which is configured with an XML property file. The look and feel
can be changed at runtime, and early demonstrations of Swing would frequently provide a way to do
this.

Relationship to AWT

Since early versions of Java, a portion of the Abstract Windowing Toolkit (AWT) has provided platform
independent APIs for user interface components. In AWT, each component is rendered and controlled
by a native peer component specific to the underlying windowing system.

By contrast, Swing components are often described as lightweight because they do not require
allocation of native resources in the operating system's windowing toolkit. The AWT components are
referred to as heavyweight components.

Much of the Swing API is generally a complementary extension of the AWT rather than a direct
replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight
component because all of the top-level components in Swing (JApplet, JDialog, JFrame, and JWindow)
extend an AWT top-level container. The core rendering functionality used by Swing to draw its
lightweight components is provided by Java2D, another part of JFC. However, the use of both
lightweight and heavyweight components within the same window is generally discouraged due to Z-
order incompatibilities.

Relationship to SWT

The Standard Widget Toolkit (SWT) is a competing toolkit originally developed by IBM and now
maintained by the Eclipse Foundation. SWT's implementation has more in common with the
heavyweight components of AWT. This confers benefits such as more accurate fidelity with the
underlying native windowing toolkit, at the cost of an increased exposure to the native resources in the
programming model.

The advent of SWT has given rise to a great deal of division among Java desktop developers with many
strongly favouring either SWT or Swing. A renewed focus on Swing look and feel fidelity with the native
windowing toolkit in the approaching Java SE 6 release (as of February 2006) is probably a direct result
of this.

Example

The following is a Hello World program using Swing.

import javax.swing.JFrame;
import javax.swing.JLabel;

public final class HelloWorld extends JFrame {
private HelloWorld() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(new JLabel("Hello, World!"));
pack();
setLocationRelativeTo(null);
}

public static void main(String[] args) {
new HelloWorld().setVisible(true);
}
}

                           Free Java Source Code | Java Programs

Core Java Programs [ PAGE 1]

Program 1

//Find Maximum of 2 nos.

class Maxof2{

 public static void main(String args[]){

   //taking value as command line argument.

   //Converting String format to Integer value

   int i = Integer.parseInt(args[0]);
        int j = Integer.parseInt(args[1]);

        if(i > j)

           System.out.println(i+" is greater than "+j);

        else

           System.out.println(j+" is greater than "+i);

    }

}




Program 2

//Find Minimum of 2 nos. using conditional operator

class Minof2{

        public static void main(String args[]){

        //taking value as command line argument.

        //Converting String format to Integer value

        int i = Integer.parseInt(args[0]);

        int j = Integer.parseInt(args[1]);

        int result = (i<j)?i:j;

        System.out.println(result+" is a minimum value");

    }

}




Program 3

/* Write a program that will read a float type value from the keyboard and print the following output.

    ->Small Integer not less than the number.

    ->Given Number.
    ->Largest Integer not greater than the number.

*/

class ValueFormat{

    public static void main(String args[]){

        double i = 34.32; //given number

        System.out.println("Small Integer not greater than the number : "+Math.ceil(i));

        System.out.println("Given Number : "+i);

        System.out.println("Largest Integer not greater than the number : "+Math.floor(i));

    }




Program 4

/*Write a program to generate 5 Random nos. between 1 to 100, and it

    should not follow with decimal point.

*/

class RandomDemo{

        public static void main(String args[]){

            for(int i=1;i<=5;i++){

                System.out.println((int)(Math.random()*100));

            }

        }

}




Program 5

/* Write a program to display a greet message according to

    Marks obtained by student.
*/

class SwitchDemo{

     public static void main(String args[]){

       int marks = Integer.parseInt(args[0]);    //take marks as command line argument.

      switch(marks/10){

        case 10:

        case 9:

        case 8:

              System.out.println("Excellent");

              break;

        case 7:

              System.out.println("Very Good");

              break;

        case 6:

              System.out.println("Good");

              break;

        case 5:

              System.out.println("Work Hard");

              break;

        case 4:

              System.out.println("Poor");

              break;

        case 3:

        case 2:

        case 1:
        case 0:

               System.out.println("Very Poor");

               break;

        default:

               System.out.println("Invalid value Entered");

    }

}

}




Program 6

/*Write a program to find SUM AND PRODUCT of a given Digit. */

class Sum_Product_ofDigit{

    public static void main(String args[]){

        int num = Integer.parseInt(args[0]);      //taking value as command line argument.

        int temp = num,result=0;

        //Logic for sum of digit

        while(temp>0){

            result = result + temp;

            temp--;

        }

        System.out.println("Sum of Digit for "+num+" is : "+result);

        //Logic for product of digit

        temp = num;

        result = 1;

        while(temp > 0){
                  result = result * temp;

                  temp--;

              }

              System.out.println("Product of Digit for "+num+" is : "+result);

    }

}




Program 7

/*Write a program to Find Factorial of Given no. */

class Factorial{

        public static void main(String args[]){

          int num = Integer.parseInt(args[0]);             //take argument as command line

          int result = 1;

          while(num>0){

                  result = result * num;

                  num--;

          }

          System.out.println("Factorial of Given no. is : "+result);

    }

}




Program 8

/*Write a program to Reverse a given no. */

class Reverse{

        public static void main(String args[]){
          int num = Integer.parseInt(args[0]);        //take argument as command line

          int remainder, result=0;

          while(num>0){

             remainder = num%10;

             result = result * 10 + remainder;

             num = num/10;

         }

         System.out.println("Reverse number is : "+result);

     }

}




Program 9

/*Write a program to find Fibonacci series of a given no.

    Example :

         Input - 8

         Output - 1 1 2 3 5 8 13 21

*/

class Fibonacci{

      public static void main(String args[]){

          int num = Integer.parseInt(args[0]);                //taking no. as command line argument.

          System.out.println("*****Fibonacci Series*****");

          int f1, f2=0, f3=1;

          for(int i=1;i<=num;i++){

             System.out.print(" "+f3+" ");

             f1 = f2;
                f2 = f3;

                f3 = f1 + f2;

            }

    }

}




Program 10

/* Write a program to find sum of all integers greater than 100 and

    less than 200 that are divisible by 7 */

class SumOfDigit{

        public static void main(String args[]){

        int result=0;

        for(int i=100;i<=200;i++){

            if(i%7==0)

                result+=i;

        }

        System.out.println("Output of Program is : "+result);

    }

}

Core Java Programs [ PAGE 2]

Program 11

/* Write a program to Concatenate string using for Loop

    Example:

                Input - 5

                Output - 1 2 3 4 5 */
class Join{

        public static void main(String args[]){

        int num = Integer.parseInt(args[0]);

        String result = " ";

        for(int i=1;i<=num;i++){

                result = result + i + " ";

        }

        System.out.println(result);

    }

}



Program 12

/* Program to Display Multiplication Table */

class MultiplicationTable{

        public static void main(String args[]){

        int num = Integer.parseInt(args[0]);

        System.out.println("*****MULTIPLICATION TABLE*****");

        for(int i=1;i<=num;i++){

            for(int j=1;j<=num;j++){

                System.out.print(" "+i*j+" ");

            }

            System.out.print("\n");

        }
    }

}



Program 13

/* Write a program to Swap the values */

class Swap{

        public static void main(String args[]){

        int num1 = Integer.parseInt(args[0]);

        int num2 = Integer.parseInt(args[1]);

        System.out.println("\n***Before Swapping***");

        System.out.println("Number 1 : "+num1);

        System.out.println("Number 2 : "+num2);

        //Swap logic

        num1 = num1 + num2;

        num2 = num1 - num2;

        num1 = num1 - num2;

        System.out.println("\n***After Swapping***");

        System.out.println("Number 1 : "+num1);

        System.out.println("Number 2 : "+num2);

        }

}



Program 14
/* Write a program to convert given no. of days into months and days.

    (Assume that each month is of 30 days)

    Example :

           Input - 69

           Output - 69 days = 2 Month and 9 days */

class DayMonthDemo{

        public static void main(String args[]){

        int num = Integer.parseInt(args[0]);

        int days = num%30;

        int month = num/30;

        System.out.println(num+" days = "+month+" Month and "+days+" days");

    }

}



Program 15

/*Write a program to generate a Triangle.

    eg:

    1

    22

    333

    4 4 4 4 and so on as per user given number */

class Triangle{

        public static void main(String args[]){
           int num = Integer.parseInt(args[0]);

           for(int i=1;i<=num;i++){

                for(int j=1;j<=i;j++){

                    System.out.print(" "+i+" ");

                }

                System.out.print("\n");

            }

     }

}



Program 16

/* Write a program to Display Invert Triangle.

    Example:

           Input - 5

           Output :

           55555

           4444

           333

           22

           1

*/

class InvertTriangle{

         public static void main(String args[]){
          int num = Integer.parseInt(args[0]);

          while(num > 0){

              for(int j=1;j<=num;j++){

                   System.out.print(" "+num+" ");

               }

               System.out.print("\n");

               num--;

          }

      }

}



Program 17

/*Write a program to find whether given no. is Armstrong or not.

    Example :

          Input - 153

          Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong{

      public static void main(String args[]){

      int num = Integer.parseInt(args[0]);

      int n = num; //use to check at last time

      int check=0,remainder;

      while(num > 0){

          remainder = num % 10;
             check = check + (int)Math.pow(remainder,3);

             num = num / 10;

        }

        if(check == n)

             System.out.println(n+" is an Armstrong Number");

        else

             System.out.println(n+" is not a Armstrong Number");

    }

}



Program 18

/* Write a program to Find whether number is Prime or Not. */

class PrimeNo{

        public static void main(String args[]){

            int num = Integer.parseInt(args[0]);

            int flag=0;

            for(int i=2;i<num;i++){

               if(num%i==0)

               {

                   System.out.println(num+" is not a Prime Number");

                   flag = 1;

                   break;

               }
         }

         if(flag==0)

                 System.out.println(num+" is a Prime Number");

    }

}



Program 19

/* Write a program to find whether no. is palindrome or not.

    Example :

             Input - 12521 is a palindrome no.

             Input - 12345 is not a palindrome no. */

class Palindrome{

        public static void main(String args[]){

          int num = Integer.parseInt(args[0]);

          int n = num; //used at last time check

          int reverse=0,remainder;

          while(num > 0){

                  remainder = num % 10;

                  reverse = reverse * 10 + remainder;

                  num = num / 10;

             }

          if(reverse == n)

                 System.out.println(n+" is a Palindrome Number");
         else

             System.out.println(n+" is not a Palindrome Number");

     }

}

Core Java Programs [PAGE 3]

Program 20

/* switch case demo

    Example :

         Input - 124

         Output - One Two Four */



class SwitchCaseDemo{

     public static void main(String args[]){

         try{

         int num = Integer.parseInt(args[0]);

         int n = num; //used at last time check

         int reverse=0,remainder;

         while(num > 0){

              remainder = num % 10;

              reverse = reverse * 10 + remainder;

              num = num / 10;

         }

         String result=""; //contains the actual output
while(reverse > 0){

   remainder = reverse % 10;

   reverse = reverse / 10;

   switch(remainder){

      case 0 :

            result = result + "Zero ";

            break;

      case 1 :

            result = result + "One ";

            break;

      case 2 :

            result = result + "Two ";

            break;

      case 3 :

            result = result + "Three ";

            break;

      case 4 :

            result = result + "Four ";

            break;

      case 5 :

            result = result + "Five ";

            break;

      case 6 :
                         result = result + "Six ";

                         break;

                    case 7 :

                         result = result + "Seven ";

                         break;

                    case 8 :

                         result = result + "Eight ";

                         break;

                    case 9 :

                         result = result + "Nine ";

                         break;

                    default:

                         result="";

                }

            }

                System.out.println(result);

        }catch(Exception e){

            System.out.println("Invalid Number Format");

        }

    }

}



Program 21
/* Write a program to generate Harmonic Series.

    Example :

            Input - 5

            Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries{

        public static void main(String args[]){

        int num = Integer.parseInt(args[0]);

        double result = 0.0;

        while(num > 0){

            result = result + (double) 1 / num;

            num--;

        }

        System.out.println("Output of Harmonic Series is "+result);

    }

}



Program 22

/*Write a program to find average of consecutive N Odd no. and Even no. */

class EvenOdd_Avg{

        public static void main(String args[]){

        int n = Integer.parseInt(args[0]);

        int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;

        while(n > 0){
             if(n%2==0){

                 cntEven++;

                 sumEven = sumEven + n;

             }

             else{

                 cntOdd++;

                 sumOdd = sumOdd + n;

             }

             n--;

        }

        int evenAvg,oddAvg;

        evenAvg = sumEven/cntEven;

        oddAvg = sumOdd/cntOdd;

        System.out.println("Average of first N Even no is "+evenAvg);

        System.out.println("Average of first N Odd no is "+oddAvg);



    }

}



Program 23

/* Display Triangle as follow : BREAK DEMO.

        1

        23
    456

    7 8 9 10 ... N */

class Output1{

        public static void main(String args[]){

          int c=0;

          int n = Integer.parseInt(args[0]);

         loop1: for(int i=1;i<=n;i++){

         loop2: for(int j=1;j<=i;j++){

                      if(c!=n){

                          c++;

                          System.out.print(c+" ");

                      }

                      else

                          break loop1;

                  }

                  System.out.print("\n");

              }

    }

}



Program 24

/* Display Triangle as follow

    0
    10

    101

    0 1 0 1 */

class Output2{

        public static void main(String args[]){

           for(int i=1;i<=4;i++){

             for(int j=1;j<=i;j++){

                       System.out.print(((i+j)%2)+" ");

                  }

                  System.out.print("\n");

              }

    }

}



Program 25

/* Display Triangle as follow

    1

    24

    369

    4 8 12 16 ... N (indicates no. of Rows) */

class Output3{

     public static void main(String args[]){

          int n = Integer.parseInt(args[0]);
              for(int i=1;i<=n;i++){

               for(int j=1;j<=i;j++){

                  System.out.print((i*j)+" ");

              }

              System.out.print("\n");

          }

    }

}

                         JAVA Date Utility

( This program Demonstrates the proper use of Date functionality in common java programming
scenarios )

Date and Time



import   java.text.DateFormat;
import   java.text.ParseException;
import   java.text.SimpleDateFormat;
import   java.util.Calendar;
import   java.util.Date;
public   class DateUtility {

/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/
        public static void addToDate(){
                System.out.println("In the ADD Operation");
        //      String DATE_FORMAT = "yyyy-MM-dd";
                String DATE_FORMAT = "dd-MM-yyyy";            //Refer Java
DOCS for formats
                java.text.SimpleDateFormat sdf = new
java.text.SimpleDateFormat(DATE_FORMAT);
                Calendar c1 = Calendar.getInstance();
                Date d1 = new Date();
                System.out.println("Todays date in Calendar Format : "+c1);
                System.out.println("c1.getTime() : "+c1.getTime());
                System.out.println("c1.get(Calendar.YEAR): " +
c1.get(Calendar.YEAR));
                System.out.println("Todays date in Date Format : "+d1);
               c1.set(1999,0 ,20);            //(year,month,date)
               System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
               c1.add(Calendar.DATE,40);
               System.out.println("Date + 20 days is : " +
sdf.format(c1.getTime()));
               System.out.println();
               System.out.println();
        }


/*Substract Day/Month/Year to a Date
        roll() is used to substract values to a Calendar object.
        You specify which Calendar field is to be affected by the operation
        (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

         Note: To substract, simply use a negative argument.
     roll() does the same thing except you specify if you want to roll up (add
1)
    or roll down (substract 1) to the specified Calendar field. The operation
only
    affects the specified field while add() adjusts other Calendar fields.
    See the following example, roll() makes january rolls to december in the
same
    year while add() substract the YEAR field for the correct result

*/

        public static void subToDate(){
                System.out.println("In the SUB Operation");
                String DATE_FORMAT = "dd-MM-yyyy";
                java.text.SimpleDateFormat sdf = new
java.text.SimpleDateFormat(DATE_FORMAT);
                Calendar c1 = Calendar.getInstance();
                c1.set(1999, 0 , 20);
                System.out.println("Date is : " + sdf.format(c1.getTime()));

               // roll down, substract 1 month
               c1.roll(Calendar.MONTH, false);
               System.out.println("Date roll down 1 month : " +
sdf.format(c1.getTime()));

               c1.set(1999, 0 , 20);
               System.out.println("Date is : " + sdf.format(c1.getTime()));
               c1.add(Calendar.MONTH, -1);
               // substract 1 month
               System.out.println("Date minus 1 month : " +
sdf.format(c1.getTime()));
               System.out.println();
               System.out.println();
        }

        public static void daysBetween2Dates(){
                Calendar c1 = Calendar.getInstance(); //new
GregorianCalendar();
                Calendar c2 = Calendar.getInstance(); //new
GregorianCalendar();
            c1.set(1999, 0 , 20);
            c2.set(1999, 0 , 22);
            System.out.println("Days Between "+c1.getTime()+"\t"+
c2.getTime()+" is");
            System.out.println((c2.getTime().getTime() -
c1.getTime().getTime())/(24*3600*1000));
            System.out.println();
                System.out.println();
        }

        public static void daysInMonth() {
                Calendar c1 = Calendar.getInstance(); //new
GregorianCalendar();
            c1.set(1999, 6 , 20);
            int year = c1.get(Calendar.YEAR);
            int month = c1.get(Calendar.MONTH);
//          int days = c1.get(Calendar.DATE);
                int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
                daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
                System.out.println("Days in "+month+"th month for year
"+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
            System.out.println();
                System.out.println();
        }

       public static void getDayofTheDate() {
               Date d1 = new Date();
               String day = null;
           DateFormat f = new SimpleDateFormat("EEEE");
           try {
            day = f.format(d1);
           }
           catch(Exception e) {
             e.printStackTrace();
           }
           System.out.println("The dat for "+d1+" is "+day);
           System.out.println();
               System.out.println();
       }

        public static void validateAGivenDate() {
                String dt = "20011223";
                String invalidDt = "20031315";
                String dateformat = "yyyyMMdd";
                Date dt1=null , dt2=null;
                try {
                        SimpleDateFormat sdf = new
SimpleDateFormat(dateformat);
                        sdf.setLenient(false);
                        dt1 = sdf.parse(dt);
                        dt2 = sdf.parse(invalidDt);
                        System.out.println("Date is ok = " + dt1 + "(" + dt +
")");
                }
                catch (ParseException e) {
                        System.out.println(e.getMessage());
                }
                catch (IllegalArgumentException e) {
                             System.out.println("Invalid date");
                     }
                 System.out.println();
                     System.out.println();
         }

         public static void compare2Dates(){
                 SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
                 Calendar c1 = Calendar.getInstance();
                 Calendar c2 = Calendar.getInstance();

                    c1.set(2000, 02, 15);
                    c2.set(2001, 02, 15);

               System.out.print(fm.format(c1.getTime())+" is ");
               if(c1.before(c2)){
                       System.out.println("less than "+c2.getTime());
               }else if(c1.after(c2)){
                       System.out.println("greater than "+c2.getTime());
               }else if(c1.equals(c2)){
                       System.out.println("is equal to
"+fm.format(c2.getTime()));
               }
               System.out.println();
               System.out.println();
        }

         public static boolean isLeapYear(int year){
                  if((year%100 != 0) || (year%400 == 0)){
                          return true;
                  }
                  return false;
         }

        public static void main(String args[]){
                addToDate();
                subToDate();
                daysBetween2Dates();   //The "right" way would be to compute
the julian day number of both dates and then do the substraction.
                daysInMonth();
                validateAGivenDate();
                compare2Dates();
                getDayofTheDate();
        }

}
                       JAVA String Utility

( This program Demonstrates the proper use of Number Formats in common java programming
scenarios )

String Utility

/*
 * NumberUtility.java
*
* Source:     http://www.freejavaguide.com
*/

import   java.math.BigDecimal;
import   java.text.DecimalFormat;
import   java.text.DecimalFormatSymbols;
import   java.util.Locale;

/**
 * Class provides common functions on number formats.
 */

public class NumberUtility {

    /**
     * Method takes Object as parameter and returns decimal number.
     * if argument is float or double and contains tailing zeros
     * it removes them. If argument is float or double then no change in
return type.
     * Change the Format of the Number by changing the String Pattern
     */
    public static String changeToDecimalFormat(Object number) {

        BigDecimal bdNumber = new BigDecimal(number.toString());
        bdNumber = bdNumber.stripTrailingZeros();           //Returns a
BigDecimal with any trailing zero's removed
        String pattern = "###,##0.0###########";             //To apply
formatting when the number of digits in input equals the pattern
        DecimalFormat newFormat = new DecimalFormat(pattern, new
DecimalFormatSymbols(Locale.US));
        return newFormat.format(bdNumber);

     }

     /* Method takes Object as parameter and removes commas from the parameter
*/
     public static double removeCommasFromNumber(Object number) {
         try {
             StringBuffer inputNo = new StringBuffer(number.toString());
             if (inputNo.length() > 0) {
                 while (inputNo.indexOf(",") != -1) {
                     inputNo.deleteCharAt(inputNo.indexOf(","));
                 }
             } else {
                 return 0.0;
             }
             return Double.parseDouble(inputNo.toString());

         } catch (NumberFormatException e) {
             return 0.0;
         }
     }

    /* Some times its required to have a fixed set of decimal places for a
     * number. We can set that by changing the precision number for a
particular
     * input BigDecimal Input String
     */
    public static String changeToRequiredDecimals(String bigDecimalString,
            int precision) {
        String newFormattedString = null;
        String afterDecimal = null;
        if (bigDecimalString == null || bigDecimalString.length() == 0) {
            return "0.0";
        }
        if (bigDecimalString.contains(".")) {
            afterDecimal = bigDecimalString.substring(bigDecimalString
                    .indexOf(".") + 1);
            int length = Math.abs((afterDecimal.length() - precision));
            if (afterDecimal.length() < precision) {
                newFormattedString = bigDecimalString;
                for (int i = 0; i < length; i++) {
                    newFormattedString = newFormattedString + "0";
                }
            } else if (afterDecimal.length() > precision) {
                newFormattedString = bigDecimalString.substring(0,
                        bigDecimalString.length() - length);
                if (precision == 0) {
                    newFormattedString = newFormattedString.substring(0,
                             newFormattedString.indexOf("."));
                    } else {
                        newFormattedString = bigDecimalString;
                    }

               } else {
                           if (precision > 0)
                               newFormattedString = bigDecimalString + ".";
                           else
                               newFormattedString = bigDecimalString;
                           for (int i = 0; i < precision; i++) {
                               newFormattedString = newFormattedString + "0";
                           }
                }
        }
        return newFormattedString;
    }

    public static void main(String args[]){
        int intVar = 10;
        double doubleVar = 10.504000;
        float floatVar = 343534534348.5687654F;
        String commaString = "343,534,535,000.0";
        BigDecimal bdNumber = new BigDecimal("1234.8765");


        System.out.println(NumberUtility.changeToDecimalFormat(new
Integer(intVar)));
        System.out.println(NumberUtility.changeToDecimalFormat(new
Double(doubleVar)));
        System.out.println(NumberUtility.changeToDecimalFormat(new
Float(floatVar)));

        System.out.println(NumberUtility.removeCommasFromNumber(commaString));
        System.out.println(NumberUtility.changeToRequiredDecimals(bdNumber.toS
tring(), 8));

     }
}
                                          Java Applet

A Java applet is an applet delivered in the form of Java bytecode. Java applets can run in a Web browser
using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand alone tool to test applets. Java
applets were introduced in the first version of the Java language in 1995. Java applets are usually written
in the Java programming language but they can also be written in other languages that compile to Java
bytecode such as Jython.

Applets are used to provide interactive features to web applications that cannot be provided by HTML.
Since Java's bytecode is platform independent, Java applets can be executed by browsers for many
platforms, including Windows, Unix, Mac OS and Linux. There are open source tools like applet2app
which can be used to convert an applet to a stand alone Java application/windows executable. This has
the advantage of running a Java applet in offline mode without the need for internet browser software.

A Java Servlet is sometimes informally compared to be "like" a server-side applet, but it is different in its
language, functions, and in each of the characteristics described here about applets.

Technical information

Java applets are executed in a sandbox by most web browsers, preventing them from accessing local
data. The code of the applet is downloaded from a web server and the browser either embeds the
applet into a web page or opens a new window showing the applet's user interface. The applet can be
displayed on the web page by making use of the deprecated applet HTML element or the recommended
object element. This specifies the applet's source and the applet's location statistics.

A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet.
The class must override methods from the applet class to set up a user interface inside itself (Applet is a
descendant of Panel which is a descendant of Container).

Advantages of applets

A Java applet can have any or all of the following advantages:

* it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it cross platform
* the same applet can work on "all" installed versions of Java at the same time, rather than just the
latest plug-in version only. However, if an applet requires a later version of the JRE the client will be
forced wait during the large download.
* it runs in a sandbox, so the user does not need to trust the code, so it can work without security
approval
* it is supported by most web browsers
* it will cache in most web browsers, so will be quick to load when returning to a web page
* it can have full access to the machine it is running on if the user agrees
* it can improve with use: after a first applet is run, the JVM is already running and starts quickly,
benefiting regular users of Java
* it can run at a comparable (but generally slower) speed to other compiled languages such as C++
* it can be a real time application
* it can move the work from the server to the client, making a web solution more scalable with the
number of users/clients

Disadvantages of applets

A Java applet is open to any of the following disadvantages:

* it requires the Java plug-in, which isn't available by default on all web browsers
* it can't start up until the Java Virtual Machine is running, and this may have significant startup time the
first time it is used
* if it is uncached, it must be downloaded (usually over the internet), and this takes time
* it is considered more difficult to build and design a good user interface with applets than with HTML-
based technologies
* if untrusted, it has severely limited access to the user's system - in particular having no direct access to
the client's disc or clipboard
* some organizations only allow software installed by the administrators. As a result, many users cannot
view applets by default.
* applets may require a specific JRE.

Compatibility issues

Sun has made a considerable effort to ensure compatibility is maintained between Java versions as they
evolve. For example, Microsoft's Internet Explorer, the most popular web browser since the late 1990s,
used to ship with Microsoft's own JVM as the default. The MSJVM had some extra non-Java features
added which, if used, would prevent MSJVM applets from running on Sun's Java (but not the other way
round). Sun sued for breach of trademark, as the point of Java was that there should be no proprietary
extensions and that code should work everywhere. Development of MSJVM was frozen by a legal
settlement, leaving many users with an extremely outdated Java virtual machine. Later, in October 2001,
MS stopped including Java with Windows, and for some years it has been left to the computer
manufacturers to ship Java independently of the OS. Most new machines now ship with official Sun Java.

Some browsers (notably Firefox) do not do a good job of handling height=100% on applets which makes
it difficult to make an applet fill most of the browser window (Javascript can, with difficulty, be used for
this). Having the applet create its own main window is not a good solution either, as this leads to a large
chance of the applet getting terminated unintentionally and leaves the browser window as a largely
useless extra window.

Alternatives

Alternative technologies exist (for example, DHTML and Flash) that satisfy some of the scope of what is
possible with an applet.

Another alternative to applets for client side Java is Java Web Start, which runs outside the browser. In
addition to the features available to applets, a simple permissions box can give Java Web Start programs
read and/or write access to specified files stored on the client, and to the client's clipboard.

                                            Java Servlet
Java Servlet API allows a software developer to add dynamic content to a Web server using the Java
platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are
the Java counterpart to dynamic web content technologies such as CGI, PHP or ASP. Servlets can
maintain state across many server transactions by using HTTP cookies, session variables or URL
rewriting.

The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions
of a web container and a servlet. A web container is essentially the component of a web server that
interacts with the servlets. The web container is responsible for managing the lifecycle of servlets,
mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

A Servlet is an object that receives requests (ServletRequest) and generates a response
(ServletResponse) based on the request. The API package javax.servlet.http defines HTTP
subclasses of the generic servlet (HttpServlet) request (HttpServletRequest) and response
(HttpServletResponse) as well as an (HttpSession) that tracks multiple requests and responses
between the web server and a client. Servlets may be packaged in a WAR file as a Web
application.

Moreover, servlets can be generated automatically by JavaServer Pages (JSP), or alternately by
template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a
pattern called "Model 2", which is a flavor of the model-view-controller pattern.

History

The original servlet specification was created by Sun Microsystems (version 1.0 was finalized in
June 1997). Starting with version 2.3, the servlet specification was developed under the Java
Community Process. JSR 53 defined both the Servlet 2.3 and JavaServer Page 1.2 specifications.
JSR 154 specifies the Servlet 2.4 and 2.5 specifications. As of May 10, 2006, the current version
of the servlet specification is 2.5.
In his blog on java.net, Sun veteran and GlassFish lead Jim Driscoll details the history of servlet
technology. James Gosling first thought of servlets in the early days of Java, but the concept did
not become a product until Sun shipped the Java Web Server product. This was before what is
now the Java Platform, Enterprise Edition was made into a specification.

Web containers

A Web container is a computer program that runs Web applications. Web containers are also
sometimes called Web engines. Like the other Java APIs, different vendors provide their own
implementation. Below is a list of some of the free web containers. (Note that 'free' means that
commercial use is free. Some of the commercial containers, e.g. Resin and Orion, make ideal
development containers and are also free to use in a server environment for non-profit
organizations).

Non-commercial web containers

* Java System Application Server is developed by Sun.
* Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available free of charge
under the Apache Software License. It is used in the official reference implementation and has a
reputation for being stable.
* Jetty
* Jaminid contains a higher abstraction than servlets.
* Enhydra
* jo!
* Winstone supports specification v2.4, has a focus on minimal configuration and the ability to strip the
container down to only what you need.
* tjws spec 2.4, small footprint, modular design
                                                 JSP

JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically generate
HTML, XML or other types of documents in response to a Web client request. The technology allows
Java code and certain pre-defined actions to be embedded into static content.

The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in
functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as
extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of
extending the capabilities of a Web server. JSPs are compiled into Java Servlets by a JSP compiler. A JSP
compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may
generate byte code for the servlet directly.

"JavaServer Pages" is a technology released by Sun.

JSP and Servlets
Architecturally speaking, JSP can be viewed as a high-level abstraction of servlets that is implemented as
an extension of the Servlet 2.1 API. Both servlets and JSPs were originally developed at Sun
Microsystems, initially created by Anselm Baird-Smith and later elaborated on as a specification by
Satish Dharmaraj. Starting with version 1.2 of the JSP specification, JavaServer Pages have been
developed under the Java Community Process. JSR 53 defines both the JSP 1.2 and Servlet 2.3
specifications and JSR 152 defines the JSP 2.0 specification. As of May 2006 the JSP 2.1 specification has
been released under JSR 245 as part of Java EE 5.

JSP Syntax

A JavaServer Page may be broken down into the following pieces:

* static data such as HTML,
* JSP directives such as the include directive,
* JSP scripting elements and variables,
* JSP actions,
* custom tags

Static data

Static data is written out to the HTTP response exactly as it appears in the input file. Thus a normal
HTML page with no embedded java or actions would be valid JSP input. In that case, the same data
would be sent in the response each and every time by the web server to the browser.

JSP directives

JSP directives control how the JSP compiler generates the servlet. The following directives are available:

* include The include directive informs the JSP compiler to include a complete file into the current file.
It is as if the contents of the included file were pasted directly into the original file. This functionality is
similar to the one provided by the C preprocessor. Included files generally have the extension "jspf" (for
JSP Fragment):

<%@ include file="somefile.jspf" %>

* page There are several options to the page directive.

import results in a Java import statement being inserted into the resulting file
contentType specifies the content that is generated. This should be used if HTML is not used or if the
character set is not the default character set.
errorPage indicates the page that will be shown if an exception occurs while processing the HTTP
request.
isErrorPage if set to true, it indicates that this is the error page.
isThreadSafe indicates if the resulting servlet is thread safe.

<%@ page import="java.util.*" %> //example import
<%@ page contentType="text/html" %> //example contentType
<%@ page isErrorPage=false %> //example for non error page
<%@ page isThreadSafe=true %> //example for a thread safe JSP

Note: Only the "import" page directive can be used multiple times in the same JSP.

* taglib The taglib directive indicates that a JSP tag library is to be used. The directive requires that a
prefix be specified (much like a namespace in C++) and the URI for the tag library description.

<%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %>

JSP scripting elements and objects

JSP Implicit Objects

The following JSP implicit objects are exposed by the JSP container and can be referenced by the
programmer:

* out The JSPWriter used to write the data to the response stream.
* page The servlet itself.
* pageContext A PageContext instance that contains data associated with the whole page. A given
HTML page may be passed among multiple JSPs.
* request The HTTP request object.
* response The HTTP response object.
* session The HTTP session object that can be used to track information about a user from one request
to another.
* config Provides servlet configuration data.
* application Data shared by all JSPs and servlets in the application.
* exception Exceptions not caught by application code.

Scripting elements

There are three basic kinds of scripting elements that allow java code to be inserted directly into the
servlet.

* A declaration tag places a variable definition inside the body of the java servlet class. Static data
members may be defined as well.
<%! int serverInstanceVariable = 1; %>

* A scriptlet tag places the contained statements inside the _jspService() method of the java servlet
class.

<% int localStackBasedVariable = 1;
out.println(localStackBasedVariable); %>

* An expression tag places an expression to be evaluated inside the java servlet class. Expressions should
not be terminated with a semi-colon .

<%= "expanded inline data " + 1 %>

JSP actions

JSP actions are XML tags that invoke built-in web server functionality. The following actions are
provided:

jsp:include Similar to a subroutine, the Java servlet temporarily hands the request and response off to
the specified JavaServer Page. Control will then return to the current JSP, once the other JSP has
finished. Using this, JSP code will be shared between multiple other JSPs, rather than duplicated.
jsp:param Can be used inside a jsp:include, jsp:forward or jsp:params block. Specifies a parameter that
will be added to the request's current parameters.
jsp:forward Used to hand off the request and response to another JSP or servlet. Control will never
return to the current JSP.
jsp:plugin Older versions of Netscape Navigator and Internet Explorer used different tags to embed an
applet. This action generates the browser specific tag needed to include an applet.
jsp:fallback The content to show if the browser does not support applets.
jsp:getProperty Gets a property from the specified JavaBean.
jsp:setProperty Sets a property in the specified JavaBean.
jsp:useBean Creates or re-uses a JavaBean available to the JSP page.

Examples of tags

jsp:include

<html>
<head></head>
<body>
<jsp:include page="mycommon.jsp" >
<jsp:param name="extraparam" value="myvalue" />
</jsp:include>
name:<%=request.getParameter("extraparam")%>
</body></html>

jsp:forward

<jsp:forward page="subpage.jsp" >
<jsp:param name="forwardedFrom" value="this.jsp" />
</jsp:forward>

In this forwarding example, the request is forwarded to "subpage.jsp". The request handling does not
return to this page.

jsp:plugin

<jsp:plugin type=applet height="100%" width="100%"
archive="myjarfile.jar,myotherjar.jar"
codebase="/applets"
code="com.foo.MyApplet" >
<jsp:params>
<jsp:param name="enableDebug" value="true" />
</jsp:params>
<jsp:fallback>
Your browser does not support applets.
</jsp:fallback>
</jsp:plugin>

The plugin example illustrates a <html> uniform way of embedding applets in a web page. Before the
advent of the <OBJECT> tag, there was no common way of embedding applets. This tag is poorly
designed and hopefully future specs will allow for dynamic attributes (height="${param.height}",
code="${chart}", etc) and dynamic parameters. Currently, the jsp:plugin tag does not allow for
dynamically called applets. For example, if you have a charting applet that requires the data points to be
passed in as parameters, you can't use jsp:params unless the number of data points are constant. You
can't, for example, loop through a ResultSet to create the jsp:param tags. You have to hand code each
jsp:param tag. Each of those jsp:param tags however can have a dynamic name and a dynamic value.

jsp:useBean

<jsp:useBean id="myBean" class="com.foo.MyBean" scope="request" />
<jsp:getProperty name="myBean" property="lastChanged" />
<jsp:setProperty name="myBean" property="lastChanged" value="<%= new Date()%>" />

The scope attribute can be request, page, session or application. It has the following meanings:
* request the attribute is available for the lifetime of the request. Once the request has been
processed by all of the JSPs, the attribute will be de-referenced.
* page the attribute is available for the current page only.
* session the attribute is available for the lifetime of the user's session.
* application the attribute is available to every instance and is never de-referenced. Same as a global
variable.

The example above will use a Bean Manager to create an instance of the class com.foo.MyBean and
store the instance in the attribute named "myBean". The attribute will be available for the life-time of
the request. It can be shared among all of the JSPs that were included or forwarded-to from the main
JSP that first received the request.

JSP tag libraries

In addition to the pre-defined JSP actions, developers may add their own custom actions using the JSP
Tag Extension API. Developers write a Java class that implements one of the Tag interfaces and provide a
tag library XML description file that specifies the tags and the java classes that implement the tags.

Consider the following JSP.

<%@ taglib uri="mytaglib.tld" prefix="myprefix" %>
...
<myprefix:myaction> <%-- the start tag %>
...
</myprefix:myaction> <%-- the end tag %>
...

The JSP compiler will load the mytaglib.tld XML file and see that the tag 'myaction' is implemented by
the java class 'MyActionTag'. The first time the tag is used in the file, it will create an instance of
'MyActionTag'. Then (and each additional time that the tag is used), it will invoke the method
doStartTag() when it encounters the starting tag. It looks at the result of the start tag, and determines
how to process the body of the tag. The body is the text between the start tag and the end tag. The
doStartTag() method may return one of the following:

* SKIP_BODY - the body between the tag is not processed
* EVAL_BODY_INCLUDE - evaluate the body of the tag
* EVAL_BODY_TAG - evaluate the body of the tag and push the result onto stream (stored in the body
content property of the tag).

Note: If tag extends the BodyTagSupport class, the method doAfterBody() will be called when the body
has been processed just prior to calling the doEndTag(). This method is used to implement looping
constructs.

When it encounters the end tag, it invokes the doEndTag() method. The method may return one of two
values:

* EVAL_PAGE - this indicates that the rest of the JSP file should be processed.
* SKIP_PAGE - this indicates that no further processing should be done. Control leaves the JSP page. This
is what is used for the forwarding action.

The myaction tag above would have an implementation class that looked like something below:

public class MyActionTag extends TagSupport {
//Releases all instance variables.
public void release() {...}

public MyActionTag() { ... }

//called for the start tag
public int doStartTag() { ... }

//called at the end tag
public int doEndTag(){ ... }
}

Add Body Tag description.

Internationalization

Internationalization in JSP is accomplished the same way as in a normal Java application, that is by using
resource bundles.

JSP 2.0

The new version of the JSP specification includes new features meant to improve programmer
productivity. Namely:

* An Expression Language (EL) which allows developers to create Velocity-style templates (among other
things).
* A faster/easier way to create new tags.

Hello, ${param.visitor} <%-- same as: Hello, <%=request.getParameter("visitor")%> --%>
Model-view-controller paradigm

Sun recommends that the Model-view-controller pattern be used with the JSP files in order to split the
presentation from request processing and data storage. Either regular servlets or separate JSP files are
used to process the request. After the request processing has finished, control is passed to a JSP used
only for creating the output. There are several platforms based on Model-view-controller pattern for
web tiers (such as Apache Struts and Spring framework).

Example

Regardless of whether the JSP compiler generates Java source code for a servlet or emits the byte code
directly, it is helpful to understand how the JSP compiler transforms the page into a Java servlet. For an
example, consider the following input JSP and its resulting generated Java Servlet.

Input JSP

<%@ page errorPage="myerror.jsp" %>
<%@ page import="com.foo.bar" %>

<html>
<head>
<%! int serverInstanceVariable = 1;%>
...
<% int localStackBasedVariable = 1; %>
<table>
<tr><td><%= "expanded inline data " + 1 %></td></tr>
...

Resulting servlet

package jsp_servlet;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

import com.foo.bar; //imported as a result of <%@ page import="com.foo.bar" %>
import ...

class _myservlet implements javax.servlet.Servlet, javax.servlet.jsp.HttpJspPage {
//inserted as a
//result of <%! int serverInstanceVariable = 1;%>
int serverInstanceVariable = 1;
...

public void _jspService( javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response )
throws javax.servlet.ServletException,
java.io.IOException
{
javax.servlet.ServletConfig config = ...;//get the servlet config
Object page = this;
PageContext pageContext = ...;//get the page context for this request
javax.servlet.jsp.JspWriter out = pageContext.getOut();
HttpSession session = request.getSession( true );
try {
out.print( "<html>\r\n" );
out.print( "<head>\r\n" );
...
//from <% int localStackBasedVariable = 1; %>
int localStackBasedVariable = 1;
...
out.print( "<table>\r\n" );
out.print( " <tr><td>" );
//note, toStringOrBlank() converts the expression into a string or if
// the expression is null, it uses the empty string.
//from <%= "expanded inline data " + 1 %>
out.print( toStringOrBlank( "expanded inline data " + 1 ) );
out.print( " </td></tr>\r\n" );
...
} catch ( Exception _exception ) {
//clean up and redirect to error page in <%@ page errorPage="myerror.jsp" %>
}
}
}

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:25
posted:6/7/2011
language:English
pages:42