Foundation of Java Programming

JGuru

Wise Old Owl
Foundation of Java Programming

This is guide for learning Java programming for budding programmers & those who are beginning Java programming.
These are very introductory programs (beginner to intermediate level).
In order to become a very good programmer you need to be

1) Very good in logical reasoning (problem solving skills)

2) In depth knowledge of Java API (Application Programming Interface)


So let's get started !!



Q) Write a program to list the contents of a directory ?

Ans) To list the contents of a directory , use the java.io.File class Use the file.list() method.

List.java

Code:
import java.io.File;
import java.util.Date;

// List the current files in the directory similar to Windows console
public class List {

    String path = ".";
    File directory = new File(path);
    String[] content;
    File file;
    String fileName;

    public List() {
        // Get the current directory contents
        content = directory.list();
        for (int i = 0; i < content.length; i++) {
            fileName = content[i];
            file = new File(fileName);
            //If it's a file
            if (file.isFile()) {
                System.out.println("" + new Date(file.lastModified()) + "       " + file.length() + " " + fileName);
            } else {
              //It's a directory
                System.out.println("" + new Date(file.lastModified()) + "   " + "<DIR>   " + " " + fileName);
            }
        }
    }

    public static void main(String[] args) {
        new List();
    }
}

This program the contents of a directory . It prints the last modified (Time) , Size of the file, filename.
If it's a directory we display the <DIR> . We use the directory.list() method to get the list of files in the current directory.
The condition file.isFile() is true if it's a file, otherwise it's a directory!

Q) Write a program to display the Size of the directory in MB or GB also count the number of files & directories ?

Code:
import java.io.File;
import java.text.NumberFormat;

public class GetDirSize {

    private int fileCount = 0;// Count the number of files
    private int dirCount = 0;// Count the number of directories
    private long fileSize = 0;
    private NumberFormat nFormat = NumberFormat.getInstance(); // To format the Numbers

    public GetDirSize(String directory) {
        System.out.println("Calculating, Please wait...");
        long dirSize = traverseDirectory(new File(directory));
        if (dirSize > 1000) {
            // Represent it in GB
            System.out.println("Size of the Directory : " + (double) dirSize / 1024 + " GB");
        } else {
            // Represent it in MB
            System.out.println("Size of the Directory : " + dirSize + " MB");
        }
        System.out.println(" No of Files = " + nFormat.format(fileCount) + ", No of Directories = " + nFormat.format(dirCount));
    }

    // Process the directory contents
    public long traverseDirectory(File dir) {
        if (dir != null) {
            //If it'a a directory
            if (dir.isDirectory()) {
                dirCount++;// Increment the count by 1
                // Get the files & directories of the directory
                String[] children = dir.list();
                if (children != null) {
                    for (int i = 0; i < children.length; i++) {
                        traverseDirectory(new File(dir, children[i]));
                    }
                }

            } else {
                // It's a File
                fileCount++; //// Increment the count by 1
                fileSize += dir.length(); // Accumulate the file size (bytes)
            }
        }
        //457 MB = 47,95,62,693 bytes
        //479562693 bytes -> 457 MB
        // ?
        return (fileSize * 457) / 479562693;
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            new GetDirSize(args[0]);
        } else {
            // If no argument is specified, use the current directory
            new GetDirSize(".");
        }
    }
}

To run the program type the following from the cmd-line

java GetDirSize D:/

If the path contains spaces , use double quotes.

For eg.,
java GetDirSize "D:\Documents3\JSession\My Programs"

Here we use a method called traverseDirectory() that traverses the entire directory to get the directory size, no. of files & directories.
We increment the directory count by 1 every time we find a directory, else we increment the file count by 1. We get the size of a File using
the method length(). We keep accumulating it until we traverse the directory.
And finally display the size of the directory. Also display the no. of files & directories.


Q) Write a progtram to list the contents of a directory recursively?

Ans)

Code:
import java.io.File;

public class TraverseDirectory {

    public TraverseDirectory(String path) {
        visitAllDirsAndFiles(new File(path));
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            new TraverseDirectory(args[0]);
        } else {
            //Show the contents of the current directory
            new TraverseDirectory(".");
        }
    }

    // Process all files and directories under dir
    public static void visitAllDirsAndFiles(File dir) {
        if (dir != null) {
            if (dir.isDirectory()) {
                System.out.println(" <DIR> " + dir.getName());
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    visitAllDirsAndFiles(new File(dir, children[i]));
                }
            } else {
                System.out.println("   " + dir.getName());
            }
        }
    }
}

To run the program

java TraverseDirectory <path>

For eg.,

java TraverseDirectory D:/

If you don't specify any path then the current directory contents are displayed.

Here we define a method called visitAllDirsAndFiles() that takes a File as argument and processes it.
It uses recursion to display the contents of the directory. Recursion is a simple & effective technique in
programming to solve some problems. Some problems like directory listing, Factorial lend themselves well in
recursion.


Q) Write a progtram to list the contents of a directory recursively using the wildcard pattern?

If the wildcard pattern is "*.java" then only Java files & directories must be displayed.
Accept the path & wildcard as cmd-line argument.


Ans)

Code:
import java.io.File;

public class TraverseDirectory2 {

    static String wildCard = "";
    int dotIndex = -1;

    public TraverseDirectory2(String path, String wildcard) {
        wildCard = wildcard;
        dotIndex = wildcard.lastIndexOf(".");
        if (dotIndex > -1) {
            // Get the last name ie., jpg from *.jpg
            wildCard = wildCard.substring(dotIndex + 1);
        }
        visitAllDirsAndFiles(new File(path));
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            if (args.length == 1) {
                new TraverseDirectory2(args[0], "");
            } else {
                new TraverseDirectory2(args[0], args[1]);
            }
        } else {
            //Show the contents of the current directory
            new TraverseDirectory2(".", "");
        }
    }

    // Process all files and directories under directory
    public static void visitAllDirsAndFiles(File file) {
        if (file != null) {
            if (file.isDirectory()) {
                System.out.println(" <DIR> " + file.getName());
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    visitAllDirsAndFiles(new File(file, children[i]));
                }
            } else {
                if (wildCard.equals("")) {
                    System.out.println("   " + file.getName());
                } else {
                    if (file.getName().endsWith(wildCard)) {
                        System.out.println("   " + file.getName());
                    }
                }
            }
        }
    }
}

To run the program type :

java TraverseDirectory2 <path> <wildcard>

For eg., java TraverseDirectory2 "." "*.java"

Will list the directories & Java files in the current directory.

Q) Write a program to count the number of Words & characters in a String?

Code:
// A program to count the words & characters in a String
public class CountWordsChars {

    String str = "Java is a great programming language";
    int charCount = 0; // To count the number of characters
    int wordCount = 0; // To count the number of words

    public CountWordsChars() {
        System.out.println("Word Count = " + count(str) + ", Charaters = " + charCount);
    }

    // Return the number of words found also count the no. of chars
    public int count(String string) {

        if (string != null) {
            //Convert the String to char array
            char[] charArray = string.toCharArray();
            char c;
            for (int i = 0; i < charArray.length; i++) {
                //Fetch every character (char)
                c = charArray[i];
                if (Character.isLetter(c)) {
                    //If the character is a alphabet
                    charCount++;
                }
                if (Character.isWhitespace(c)) {
                    // If it's a whitespace (' ')
                    wordCount++; // Increment the word count by 1
                }
            }
            // At last we increment the wordCount by 1
            return ++wordCount;
        }
        return 0;
    }

    public static void main(String[] args) {
        new CountWordsChars();
    }
}

Here in this program we declare a method called count() that take a String as argument and finds the number of words in a String,
as well the characters in a String.


Q) Write a program to print the prime numbers from 1 to 100000 ?

Ans)

Code:
public class Prime {

    int MAX = 100000;

    public Prime() {
        for (int i = 0; i < MAX; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
    }

    // Checks whether a number is prime or not
    public boolean isPrime(int n) {
        for (int i = 2; i < n / 2; i++) {
            return n % i != 0;
        }
        return false;
    }

    public static void main(String[] args) {
        new Prime();
    }
}


Q) Write a program to print the Fibonacci series?

Ans) The famous sequence of numbers called Fibonacci series.
Each term is found by adding the two previous ones: 1+1 is 2, 1+2 is 3 ,2+3 is 5, 3+5 is 8 and so on.
The Fibonacci has applications in diverse fields from Sorting methods in Computer Science.

Code:
public class Fibonacci {

    public static void main(String[] args) {
        long limit = 429406729;
        long next = 0;// next to the last term
        long last = 1;// last term
        long sum = 0;

        while (next < limit) {
            System.out.print(last + " ");
            sum = next + last; // Add last two terms
            next = last;// Variables move forward
            last = sum; // in the series
        }
    }
}

Q) Write a program to display the Factorial of the given number

i) using recursion
ii) without recursion

Ans)

i) Using Recursion

Code:
public class Factorial2
{
    public static void main(String[] args) {
        if(args.length != 0) {
            int num = Integer.parseInt(args[0]);
            System.out.println(factorial(num));
        }
    }
    // The "factorial" static method calculates the factorial value for the
    // specified integer passed in:
    public static int factorial(int n)
    {
        if(n <= 1)
          return 1;
        else
          return n * factorial(n-1);
        // The same can be expressed using the ternary operator
        //return((n <= 1) ? 1 : (n * factorial(n-1)));
    }
}

ii) Without Recursion

Code:
public class Factorial {
    public static void main(String[] args) {
        if(args.length != 0) {
            int num = Integer.parseInt(args[0]);
            System.out.println(factorial(num));
        }
    }
    // Use a while loop
    private static int factorial(int fact) {
        int result = fact;
        if (fact == 0)
            return result;
        else {
            while (fact != 1)
                result *= --fact;
        }
        return result;
    }
    
    // Use a for loop
    private static int factorial2(int fact) {
        int result = 0;
        for (int i = fact; i > 0; i--) {
            result *= i;
        }
        return result;
    }
}

Q) Write a program to animate over a sequence of images?

Ans) Here is the same program to animate over a sequence of Images!!

You can extract images from a VCD song using VirtualDubMod software!!

VirtualDubMod Hompage

Code:
// Animating over a sequence of images!!

import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;

public class AnimApp extends JComponent implements Runnable {

    private Image image;
    private int frame = 0;
    // Total no. of Images
    private int totalImages = 97; // total no.of images
    private Clip clip;
    private static int width = 345 + 345/2;
    private static int height = 208 + 208/2;
    // Display each image
    private int delay = 135;    // 35 fps
    private String path = "resources/images";
    private String prefix = "SM";
    
    // NOTE you should create a directory called 'resources/images' in the current directory and place some images like SM1.png,
    // SM2.png, SM3.png ... SM60.png 
    

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //Image image = images[frame];
        if (image != null) {
            // Draw the current image
            int x = 0;
            int y = 0;
            // Scale the Image to double its size
            g.drawImage(image, x, y, width, height, this);
        }
    }

    public Image getImage(int frame) {
        try {
            return ImageIO.read(new File(path + prefix + frame + ".png"));
        } catch (IOException ioe) {
        }
        return null;
    }

    public void print(String message) {
        System.out.println(message);
    }

    @Override
    public void run() {

        try {
            while (true) {
                // Fetch the Image
                image = getImage(frame);
                // Move to the next image
                frame = (frame + 1) % totalImages;
                // Causes the paint() method to be called
                repaint();
                // Wait
                Thread.sleep(delay, 200);
            }
        } catch (InterruptedException e) {
        }
    }

    public static void showFrame() {
        AnimApp app = new AnimApp();
        // Display the animation in a frame
        JFrame frame = new JFrame();
        frame.getContentPane().add(app);
        frame.setSize(width, height);
        frame.setResizable(false);
        frame.setLocationRelativeTo(app);
        frame.setVisible(true);
        frame.setTitle("Animation App");
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        (new Thread(app)).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimApp.showFrame();
            }
        });
    }
}

*s21.postimg.org/fi5gf1hxv/Animation_App.png


Q) Write a program to print the Directory report (file types , size (MB)) , Use recursion to process the sub-directories?
Also calculate the entire directory size(in GB) ?

Ans) Here is the complete code!!

Code:
/**
 * @(#)FileExtensions.java
 *
 * @author JGuru
 * @version 1.00 2015/7/30
 */
import java.io.File;
import java.util.Vector;

public class FileExtensions {

    private String path = "."; // This represents the current directory
    private File file = new File(path);
    private Vector<String> fileExtension = new Vector<>();
    private String extension = "";
    //Total size of the directory
    private long totalSize = 0;
    private int MAX;
    //Array holding file sizes
    private int[] fileSizes;

    public FileExtensions() {

        // Get all the unique file extentions
        getFileExtensions(file);
        System.out.println("\n\nDirectory Report for " + file.getAbsolutePath() + "\n\n");
        System.out.println("Directory Total Size : " + toGB(totalSize) + " GB");
        // Create an array to hold files size
        MAX = fileExtension.size();
        fileSizes = new int[MAX];
        // get all the files size
        getFilesSize(file);
        System.out.println(" File Type Size (in MB)" + "\n");
        long size;
        for (int i = 0; i < MAX; i++) {
            // Convert the size in bytes to MB!!
            size = toMB(fileSizes[i]);
            // Print fewer !!
            if (size > 10) {
                System.out.println(fileExtension.get(i) + "\t\t" + size + " MB");
            }
        }
    }

    // Process all files and directories under the directory
    public void getFileExtensions(File file) {
        if (file != null) {
            // The file is a directory
            if (file.isDirectory()) {

                String[] children = file.list();
                if (children != null) {
                    for (int i = 0; i < children.length; i++) {
                        getFileExtensions(new File(file, children[i]));
                    }
                }

            } else {
                // Accumulate the file size
                totalSize += file.length();
                extension = getExtension(file);
                if (!isDigit(extension)) {
                    if (!fileExtension.contains(extension)) {
                        fileExtension.addElement(extension);
                    }
                }
            }
        }
    }

    public String getExtension(File file) {
        if (file != null) {
            String fileName = file.getName().toLowerCase();
            int dotIndex = fileName.lastIndexOf(".");
            return fileName.substring(dotIndex + 1);
        }
        return null;
    }

    // Returns the Files size in MB
    public void getFilesSize(File file) {
        if (file != null) {
            if (file.isFile()) {
                for (int i = 0; i < MAX; i++) {
                    if (getExtension(file).equals(fileExtension.get(i))) {
                        fileSizes[i] += file.length();
                    }
                }
            }

            if (file.isDirectory()) {
                String[] children = file.list();
                if (children != null) {
                    for (int i = 0; i < children.length; i++) {
                        getFilesSize(new File(file, children[i]));
                    }
                }
            }
        }
    }

    // Converts bytes to GB
    long toGB(long bytes) {
        // 1 GB = 1074213536.686391 bytes
        //1074213536.686391 bytes - 1GB
        //bytes ?
        return (long) (bytes * 1 / (1074213536.686391));
    }

    public FileExtensions(int MAX, int[] fileSizes) {
        this.MAX = MAX;
        this.fileSizes = fileSizes;
    }

    // Converts bytes to MB
    int toMB(long bytes) {
        return (int) ((bytes * 457) / 479562693);
    }

    // Check whether the first character is a digit
    boolean isDigit(String str) {
        if (str != null) {
            char c = str.charAt(0);
            if (Character.isDigit(c)) {
                return true;
            }
        }
        return false;
    }

    void print(String str) {
        System.out.println(str);
    }

    public static void main(String args[]) {
        new FileExtensions();
    }
}

The program recursively searches a given directory for files (caches the extensions) & finds the sizes of the files with all the extensions.
The method toGB() converts the size in bytes to GB. Similarly the method toMB converts the size from bytes to MB.


Q) Write a program to find the largest word in a String?

Ans) Here is the solution!!

Code:
// Find the Largest word in a String
/**
 *
 * Author JGuru - dated 31-12-2005
 */
class LargestWord {

    String str = "Hey Java is great programming language oops!!";
    //Convert the String into a String array (easy for comparing items)
    String strArr[] = str.split("\\s");

    // Compare the String Length of two Strings
    // return the bigger length one
    private String compare(String str1, String str2) {

        if (str1.length() > str2.length()) {
            return str1;
        } else {
            return str2;
        }
        //return str1.length() > str2.length() ? str1 : str2;
    }

    LargestWord() {
        String tmp = "";
        for (int i = 0; i < strArr.length; i++) {
            //Initialize variable tmp with the element '0' in the array
            if (i == 0) {
                tmp = strArr[0];
            } else {
                // Compare both strings , store the result in tmp variable
                tmp = compare(tmp, strArr[i]);
            }
        }
        System.out.println("Largest word = " + tmp);
    }

    public static void main(String[] s) {
        new LargestWord();
    }
}

Here we want find the largest word in a String. First we split the String into a String array.
We use a method called compare() to compare two strings , return the one with bigger length.
We iterate through the array ans atlast find the bigger string.

17) Write a program to print the factorial of a number (very very big number) ?

Ans) int, long, double can't hold very very very big numbers!!!

The solution is to use java.math.BigInteger!!
BigInteger can hold very very very long numbers!! It treats numbers as Strings.

Here is the code.

Code:
import java.math.BigInteger;

// Big Numbers Factorial
public class FactorialBig {

    public static void main(String[] args) {
        if (args.length != 0) {
            int num = Integer.parseInt(args[0]);
            System.out.println(factorial(num));
        }
    }

    private static BigInteger factorial(int fact) {
        BigInteger m = new BigInteger("1");
        for (int i = fact; i > 0; i--) {
            m = m.multiply(new BigInteger("" + i));
        }
        return m;
    }
}

To run this program type :

java FactorialBig 10000

Here is the output!!
Code:
2846259680917054518906413212119868890148051401702799230794179994274411340003764443772990786757784775815884
0621423175288300423399401535187390524211613827161748198241998275924182892597878981242531205946599625986706
5601615720360323979263287367170557419759620994797203461536981198970926112775004841988454104755446424421365
7330307670362882580354896746111709736957860367019107151273058728104115864056128116538532596842582599558468
8146430425589836649317059251717204276597407446133400054194052462303436869154059404066227828248371512038322
1786446271838229238996389928272218797024593876938030946273322925705554596900278752822425443480211275590191
6942542902891690721909708369053987374745248337289952180236328274121704026808676921045155584056717255537201
5852132829034279989818449313610640381489304499621599999359670892980190336998484404665419236258424947163178
9611920412331082686510713545168455409360330096072103469443779823494307806260694223026818852275920570292308
4312618849760656074258627944882715595683153344053442544664841689458042570946167361318760523498228632645292
1529423479870603344290737158688499178932580691483168854251956006172372636323974420786924642956012306288720
1226529529640915083013366309827338063539729015065818225742954758943997651138655412081257886837042392087644
8476156900126488927159070630640966162803878404448519164379080718611237062213341541506599184387596102392671
3276546986163657706626438638029848051952769536195259240930908614471907390768585755934786981720734372093104
8254756285677776940815640749622752549933841128092896375169902198704924056175317863469397980246197370790418
6832993101655415074230839317687836692369484902599960772968429397742753626311982541668153189176323483919082
1000147178932184227805135181734921901146246875769835373441456013122615221391178759688367364087207937002992
0382791980387023720780391403123689976081528403060511167094847222248703891999934420713958369830639622320791
1562404425080891991431983712044559834404755675948921210149815245454359428541439084356441998422485547853216
3624030098442855331829253154206551237079705816393460296247697010388742206441536626733715428700789122749340
6843364428898471008406416000936239352612480379752933439287643983163903127764507224792678517008266695983895
2615075900734921519759265919270887320259406638211880198885474826604834225645770574397312225970067193606176
3513579529821794290797705327283267501488024443528681645026165662837546519006171873442260438919298506071515
3900311066847273601358167064378617567574391843764796581361005996386895523346487817461432435732248643267984
8198145843270303589550842053478849336458248259203328808902578238823326577020524897093704721021424841334246
5268206806732314214483854074182139621846870108359582946965235632764870475718351616879235068366271743711915
7233611430701211207676086978515597218464859859186436417168508996255168209107935702311185181747750108046225
8552131476489749066075287708289766751495100968232968973200062239288805665803614031128546592908407803397490
0664953205873164948093883816198658850827382468034897864757116679890423568018303504133875731972630897909435
7106877973016339180878684749436335338933735869064058484178280651962758264344292580584222129476494029486226
7076183298822900407239040373316820741741325165668844307933944701920890562078838758534251282095735930701819
7708340163817638278562539516825426644614941044711579533262372815468794080423718587423026200264221822694188
6262121072977766574010183761822801368575864421858630115398437122991070100940619294132232027731939594670067
1369537709789777811828824244292086481613417956201747183160968766104314049795819823644580736820940402221118
1530051433387076607063149616107771117448059552764348333385744040212757031851527298377435921878558552795591
0286644579173620072218581433099772947789237207179428577562713009239823979219575811972647426428782666823539
1568785727162014619224426626670840076566562580710947439874011077281166991880626872662656558334566500789030
9050656074633078027158530817691223772813510584527326591626219647620571434880215630815259005343721141000303
0392428664572073284734817120341681863289688650482873679333984439712367350845273401963094276976526841701749
9075694798275782583522999431563332210743913155012445900532470268031291239229797903041758782339862237353505
4642646913502503951009239286585108682088070662734733200354995720397086488066040929854607006339409885836349
8654661367278807487647007024587901180465182961112770906090161520221114615431583176699570609746180853593904
0006789287854882785093863735370390404941268461899127287156265500127083303995025787993170543188275265922581
4948950746639976007316927310831735883056612614782997663188070063044632429112260691931278881566221591523270
4576958675128219909389426866019639044897189185974729253103224802105438410443258284728305842978041624051081
1032691400190056878439634150269652104892027214023216023489858882737142869533968175510628747090747371818801
4223487248498558198439094651708364368994306189650243288353279667190184527620551085707626204244509623323204
7447078311904344993514426255017017710173795511247461594717318627015655712662958551250777117383382084197058
9336732372445328045653717851496030880258028406784780941464183865922665280686797884325066053794304625028710
5104929347267471267499892634627358167146935060495110340755404658170393481046758485625967767959768299409334
0263872693783653209122877180774511526226425487718354611088863608432728062277766430972838790567286180360486
3346489337143941525025945965250152095953615797713559579496572977565090269442808847976127666484700361964890
6043761934694270444070215317943583831051404915462608728486678750541674146731648999356381312866931427616863
5373056345866269578945682750658102359508148887789550739393653419373657008483185044756822154440675992031380
7707353997803633926733454954929666875992253089389808643060653296179316402961249267308063803187391259615113
1890359351266480818568366770286537742390746582390910955517179770580797789289752490230737801753142680363914
2447202577288917849500781178893366297504368042146681978242729806975793917422294566831858156768162887978706
2453124665172762275829549342148365886891929958740209569600024356030528982986638689207699283403054971026651
4322306125231915131843876903823706205399206933943716880466429711476743564486375026847698148853105354063328
8450620121733026306764813229315610435519417610507124490248732772731120919458651374931909651624976916575538
1219856643220797866630039893866023860735785811439471587280089337416503379296583261843607313332752602360511
5524227228447251463863269369763762510196714380125691227784428426999440829152215904694437282498658085205186
5762929927755088331286726384187132777808744466438753526447335624411394476287809746506839529821081749679588
3645227334469487379347179071006497823646601668057203429792920744682232284866583952221144685957285840386337
7278030227591530497865873919513650246274195899088374387331594287372029770620207120213038572175933211162413
3304227737424163535535879770653096476858860773014327782903288947958184043788585677729320944767786693575374
6004814237674119418267163687048105691115621561435751629052735122435008060465366891745819654948260861226075
0293062761478813268955280736149022525819682815051033318132129659664958159030421238775645990973296728066683
8491662579497479229053618455637410347914307715611686504842924902811029925296787352987678292690407887784802
6247922275073594840581743908625187794689004594206016860514277224448627246991114620014988066272353883780938
0628544384763053235070132028029488392008132135446450056134987017834271106158177289819290656498688081045562
2337030672542512772773302834984335957725759562247037077933871465930330886296994403183326657975146765027173
4629888377739784821870071802674126599715872803544047843247867490712792167289852358848694354669225510133760
6377915164597254257116968477339951158998349081888281263984400505546210066988792614558214565319696909827253
9345157604086134762587781658672944107753588241623157790825380547469335405824697176743245234514984830271703
9654388773763735819173658245427334749042426294601129988191656371384711184915691505476814041174980145426571
2394204425441028075806001388198650613759288539038922644322947990286482840099598675963580999112695367601527
1730868527565721475835071222982965295649178350717508357413622825450556202709694174767992592297748886274113
1458767614753145689532809311705269648641018740767329698664923643738256547502281647192681555988319662984830
7776666840622314315884384910519058281816740764463033300119710293036455866594651869074475250837841987622990
4159117936827997606541860887216266548864923443910309232569106337759697390517811227646684867917360494043937
0333935190060938726839729924647848372727477097746669359978485712015678900024194726922097498412732314740154
9980920381459821416481176357147801554231599667838534854486406936410556913531335231184053581348940938191821
8986948253839609899428220275993396352062177053435720733962505742167694651016084956014393032443042715760995
2730868460920442222610315422998444480211009816133382482737521899873820531516492713449810595015997480057159
1912202154487748750103473246190633941303030892399411985006225902184164409988173214324422108554248620896250
2606043981801890263177811466174549997714406652328638463638470016556181538610981881111817341913055050248603
4585675558563751172977429932907494423657966833270091836733897734790175924888566037995277154056908301731172
3894140326159612292912225191095948743805673381278538616491842786938417556898047100859868372033615175158097
0225662752001609561922299254017598785220385459137717839763898111984858032910487516669211951045148966777615
9824946872742066343759320785261892268728552767132488326779415291283916540796834419023909480367668870783801
1367042753971396201424784935196735301444404037823526674437556740883025225745273806209980451233188102729012
0429979890054231262179681352377580411625114591759932791341765072928267622368972919605282896752235214252342
1724784186931739746041187763460462563713530980159061773675871533680395855905482736187611215138467343288432
5090045645358186681905108731791346215730339540580987172013844377099279532797675531099381365840403556795731
8941419765114363255262706397431465263481200327200967556677019262425850577706178937982310969867884485466595
2732706167030891827720643255191939367359134603775708319318084592956515887524459760172945572050559508592917
5506510115665075521635142318153548176884196032085050871496270494017684183980582594038182593986461260275954
2474333762262562871539160690250989850707986606217322001635939386114753945614066356757185266170314714535167
5300749921386520776852382488460062373589660805495165240648054729586991869435881119783368014148807832121345
7152360124065922208508912956907835370576734671667863780908811283450395784812212101117250718383359083886187
5746612013172982171310729447376562651723106948844254983695141473838924777423209402078312008072353262880539
0626601818605042493878867787249550325542428422659627105069264607176746750233780567189345011073737703411934
6113374033865364675136733661394731550211457104671161445253324850197901083431641989998414045044901130163759
5206757155675094852435802691040776372109986716242547953853128528899309565707292186735232166660978749896353
6261052982147256948279999622082577584098845848425039118944760872968518498397636791824226657116716658015791
4500811657192200233759765317495922397884982814705506190689275625210462185661305800255607974609726715033327
0323100252746404287555565468837658388025432274035074316842786206376970547917264843781744463615205709332285
8728431569075625556930555881882260359000673933995250437988747093507927618111627630977125798397599652661212
0317495882059435754883862282508401408885720583992400971219212548074097752974278775912566026443482713647231
8491251808662787086261166999896348124058036847945873648201246536632288890116365722708877577361520034501022
6889018910167357205866141001172366476265783539636429781901164705617027963192233229422873930923333074825893
7626198997596530084135383241125899639629445129082802023225498936627506499530838925632246794695960669046906
6862926450062197401217828998729797048590217750600928933289572723920195899944719451473608507704007257174393
1814846190940626954528503052634100056502222615230936488288712204645426770057714899433514716250425236517371
0266068647253458120186683273953682547456536553597546685788700056988360286686450740256993087483441094086086
3037079082952405767316849418558104824753047589233928015713028241062349999459323905214098565595656613460033
9615051516475885274221473251799954897799284952274602985566670081187120085615501645740048417021030303899633
9253337466556817824410737409336919294104632307731994759826307383499600770372410446285414648704116273895649
8345551621656851145513838220470054839966717062464675661012913820489091211172293862442531589130669874620455
8724480605282937814830262216454228042175776076236545982822307081550346940493831775505330509469899947611941
9231280721807216964378433313606760676965187138394338772485493689061845700572043696666465080734495814495966
3062466986798328725863000642152202101718139173252751736722626214549454685060063346927138383117158497530926
4325248696022005909980266376538622546326516841496330636954808655110125675771789061669475834404348621848536
9591602172030456183497524162039926441331651884768606830642004858557924473340290142588876403712518642229016
3336915850632737271995963629127833447862188878710095337535510546889802363782637149269132895643394408994701
2145213457211771565759145173489519501680062135392717541984387616354347980692088666622709951237170624192491
4282576453125769939735341673046864585181979668232015693792684926999983992413571941496882273704022820805171
8080034004806152617920139789451862952905584407037383005335524211539033851858293667791906101163062336731444
1920289385720185556959633083361545029042482230929708712478800201738307206048268015667539759378993179351579
9958929562156307338416294599900276730832827716595064217966523190439250543226753731811755315476780739470338
9311851072977243183789726749574557781833454959423173535582910469673153912759756872818616911610831563372326
3996888149054394326119718227499679117662855340186019831580962998179110720880499229201606205906727127359946
1871634945774995805337947187105456452579396024210259136415528398395201773012712514892051061708228008339985
6657866469207371142696823017704163248294794095586946990893791651910063051853521023451897981276191430618643
6270308197712499275105673290948120205774710068770337970893422920718390374416750349381883634222928494679066
0285674293251642569044363473087656797056595677285291081242733154406580199802711579126254172797452862574865
9219332938059152395247355188871198603913196542875762901905039640835602462775343144091556421817294599415960
6197962263324271586342597794734868207480202153873472970799975333298778553105382016216979188038075300633435
0766147737135939362651905222242528141084747045295688647757913502160922040348449149950778743107189655725492
6512826934895157950754861723413946103651766167503299486422440396595118822649813159250801851263866353086222
2349109462905931782940819564048470245653830543205650692442267186325530764076187208678039171135636350126952
5091291020496042823232628996502758951052844368177415730941874894428065427561430975828127698124936993313028
9466705604140843089422311409127222381484703643410196304136307367710600381595908297464101144213583210425743
5835022073717321974508903557318735044582723877072827140616299791962935722410447715505165253586754410939507
9218369015261138440382680054150924346511711436477899444553993653667727589565713987505542990824585609510036
9346631006737147080299276569334355009271898540501099174749799915543920319089619676154446860481754006956894
7146392824538380701044418104550617130516058435581752103233846582920107103006112428340745860700606019483055
1364867021020364708470807422704371893706965688795617928713045224516842027402021966415605280335061293558739
0793935244040925842483806071774446099640352218910229619090325690423813744924949068923143308842243996313963
9154585406528632646880758114874837140828417645522638631352026489401626249480238856823159910295262033712644
9279901938211134518446387544516391239377974190576649911764237637722282802318465738050121277809680315691477
2649102575035087587922481102235445244108724485657007551871321465920935485045528291707495967754044507794948
3637175606232692575741281311024191037333808043432531088469483155572940226539497291381758133861945705779956
1808755951413644907613109617155928376585840036489374076822257523935988731081689667688287403837192827690431
5141069976783038190856907130919313408460195111474827663507246765349220400586266776329355166319396224989799
1270800446598226489912522681312430052810499505859567652712359149444261255443761864502920288135858287178957
7224116380815161831603129728796987480139828621645629196153096358337313619724773332353025466571196902611237
3806290302429042757945490300226608474465131617416919168517464649454596960053308852527920834724952354731106
7410909922354105550629968764215395124935598631134666172511689078563332893556915044948518911348830187636510
0638502565916433021928565596263914382895068324838727165616560111531517055222955765944972454788815532316417
4532671679788611411653555975883319796380709629988807673036169403177364481404278677842512324499746934213482
1717959519069820460299717200117485730388971920559741474245301113586976625660777097022563326170110846378479
5555258504578058879440756064974127974530918418405207558526462208821483646754652237609210787539190454684852
3497599860449433228280731206799224024775075141058907746273343190912554513522253292759138420473846030561631
5423655293531227838975944651578733734346317228000103138042548140402209058040505600386093740343506886308143
4683848900708938565050027569059678069404698435184535134141031615133683043714786642925389717165978629010728
4007589397003883177426481637251132773699268277094653425835961118819550924620621539781211972447626237715344
5204806981908252494396396225111383117742897853582559083249048049751604710425756975344255151577981560037084
7230603484753977513688390404316017486248871339311818523029425425676202485688393970836748788453789172574145
1559179190353985350772009005949793529394596312134455033682606900598287177235333752219419155473037420623432
6289296839701505889219111204924986479205341087234911543098718216005576220907573230462610659774494765834631
3025598636315029959672352476943975462530206788193304372284800209305354155640664838569378144603138697563459
2002334626069959555134847541478911808303298164215874529229526789379256477520290526753493566737442931826733
7457164246540774826790104677875908540813053144717645586989416966894043648995246524744398834958387120629648
5413357553813419500498743813369062703973874586604296871595820715766599826607317005624465541763024501349159
5672889426197461444969086716558597827292287027237748350973629010191304178127357730377818040815891360052073
1580694103430500318434934236026924473306001386111978177447266960892832105254311649603342010203260386367253
2889648333405862204843616575362001468405476649666473566979572953394809138263703324220930839366954980688240
4916220631479114946420425000224504134255585619374429052572524363200544874415243073052150704910204340765724
7686509575117412541372953164452176557723534860182156683335252053283000010834400876226684381702323560564515
8256954177359197813649975559601912567744942717986360045847405209290089397315276024304951653864431388147876
9775414787574326101598797097588556258067661979730984724607694848211279484279765366070550516391044150225544
2032972129203300935335668729459591232796588637648689418843364054849400957496579165768721392733015355509786
5114767947399690623184878377515462613823651665956337209345708208301840482797005728071432925727577436229587
0473616416097318172415942042703660664040897402455215307252273886372418596464552236732604111645984640200102
1692082331515538882107152719126787653179507190820452510044782129131854405481449415186711420710369389112912
5012750853466337717749376016543454696390042711129829255096830420665725364279472200020835313883708781649957
1897176293387948542712768826520037663259245616148687448974715193662192756658524621144574070106753804275641
8444083480520383826505260169858406008478842242188785692789775181044280547442722945516742033568646060997797
3124950433321425205053675790499520783597650415379001132579536040655172654879022173595444151139429231648950
6631778130390574620824491719213118641296337046614064569001789423567387755231309527859127745332418554424844
8449366421073134881918064018922231730215664581347318644999790578166209146987071803938888578128074022636360
2294114354869871402143572055947730892808653678920201935102605361567924483276749476117858316071865710310842
2005602595451151913913091195444478443610327418761023388433916875892334237908598419682665256106287512375723
1849147495194598572889793498179176182265248040823712810979077263886428606791708228857585270347083971456161
9926247844794692794996845945632382702297364173503430783194115698247820013290851202878474805860188960045901
7459740556307327144876790852888679788099706952406810066256114400149834135808897372468440649488570741676879
1641322420537365406733018639249791091547478595916386559750709058117592489950221479925094563558251431581446
4060134283490422798357939659258985200763845646681640732681928346007767285876284900068874564639274964415904
0340336723378144915970329417872941550610541295154001593938516639293256774295575494800466582735796539909402
3354364464937682727254187362754753297680819032533614108643308423777173899522153676309530204590243869463270
2895293994483013577589081214884558493819874505920914067209522469096263076941753340983698859363700314973728
9779963600186265001749292900879311899978229637123066422979961635825726001122889836476514180459757700421208
3394936465964733646428904449932539622709190737370577205132281595786322759191278605429786295318861555980472
8160710864132803585400160055575686855791785977899197902656592621283007225351401525973569300729015392211116
8685047404021721744420517380002513610004945341193243316683442431259630988123969622023588583955878316851948
3312665357735324437993568321526917704224903457453485891381258268136690892947680905263556063811966130606393
6938411817713545929884317232912236262458868394202889981693561169865429884776513118227662526739978808816010
4706515423350156713537448170862343146625311902910401522629271040992850724188433290072777947541116375521765
6358931632663604938121840183751281888477116897547948376766408484275362307401954218321798549626066659034792
5816342392670947839907062923166535037285019751324813803837070894638925470887039085723581006130628646664710
0061043521157789266134322146553114118825969429262845221090266884149757633415549211355812546165580782734701
1581400600834576213313038998784327065371995670957084738578609264918885837873923916555426357730129224364160
4062551736892335636568854365851646207821875741724364525814143487632761341752707376754922276287782264765154
3153415857137735227303354033763642042580342572647496862178236669513534106773784211313711319873732228918052
7506281227771641249441240120712595431999174657474589258261371282555553508040414394455729599455463560848725
1339462936358940832098964801619583130429720964794128539388996265368928263807677168759588502216464582430940
1650096887973661577335603168367103868952282709415095452227440027354992536702147159940565448138421863801287
9990082093357632073636940599142426371829400061374190057951309629854533074819780256830108967287380223482048
8862973130369689882640657904781562389778485365025691064231795736025330908763271784911189748432246868086340
3839641761276057886465744722848249326874430625512205069551684646694771836819114328735448158363505481464110
9996014339059579976629064688129502503915092363301107607063286331739337814969338024758003505278978275575092
8604039420506342939327064636161031822879248152679306862749237275631852225654266008556849497720285909150930
4954259674736483314372363495554489015986684083621769135596560395196704253688634823695871294625247590317768
1318497758827657674048255813650210364958550570325921995767533426422378372358605850940358397710347667064478
8640831109650302565215607464019652716999732373465237173456595514559493098166644006211599349133180135150528
6518421788280263433259347558507611686977091255800561856837105408560812495194031480646187194025776632852670
1969838756756152469675902810686489686929331595435209768752713720161616093117425019970928968494003469624232
5688410665113304377412256176258658941236728171145526423894512631717834790276921171452887352955019336759218
9080060486337377867281806102547825704367884495035189257874998366947859086129755430841226770609543476121337
1743315678379016201233723702333831641470642859218597761015823272199791506287186818675098166553774501302088
0333904353639770263363809098526494532628146558065546504823486429495390613257400496912888340518222933644476
6838550379679758096199835758070277595359687882261946596122230445492756002749551685835425822953360428344263
1847806882539545074669187789776540603843251284381281131685620460861728940822965862617442076692029742793008
8129519854678713548623236610413216581279267151545961594352593456757445992307889205519540082316409719591250
0254552375031067356397488355424804496813830306718519314913357892021236053081999520205845034234999321509626
3497781245665830468058182456352481462584933192619540688481844644524842948606301616947666324262523147632237
1109695369483824482316410396224507675405614287468267835723704895606990652792688455844512046654853378534026
6466450423396384882577198749536113004942155937355452119261867214782654168856040949282900566168838076376566
9051074089251054916522296887867696863165251491770149990006663734454612026278070192569870622554092894519471
8778004306130021828287425867048748480826948573444778244078734102710824870269523830804910960482013901294024
6312448001593366702126583176778797529659634725768943265404358892672939506878608306262662632873920873273025
4791009993211338897780781433672879144876837368646774852877773740354747287164421776782071296450627088097863
7928144071192505141148004907055608097229299792441471062852247029870699869227676341773513258602908903875707
4543680778764223853337006920896163510092335873039865439060718809525575533803647258950073067721225280781794
7105648117137855745105769104432292542902414943358839609367932136169695425129973103103280443695450192984382
0842383121265825740594509426942777307124802176915781835720087170538773256017987133005505911377823841791640
2808414096238208476373930139307784285545452223675598246662506087542848761041456613622276424059143044555808
5631818093523040779389161490211629240051507491406844320323036560995487862099919430656445533254713555736531
8516011700321550690787716752062881527885897149410320986984083048966524351030502444679931779147659103428949
1290541203616016956712221408063694059403045521862128799330928562310224184463652890974446401519866231838819
6244482259078358591404368619301904145896269387890703498216986869693444808621399053459179282665430479820721
9634134755646525483143771156678459077797196510772468000293581546267646310224279007313631352522067062951125
9358744731341864924972827847966445854489629329052620580652485887070208793891344760833446531709392424082493
2800891573131954134831182092775248688054873394331586756266612217935505119060999291137944563499562739189845
9029021713155706096267881673302940198464237390445098028030948975981259252055850973537436556825780313681902
0071516756938272818188245875417107211808065564480391225045370894226953583821925350756928340956398592655997
4039131670929004399627597683037521750336087902829567306886226307772973353385368266873451903570970968732232
3738300494090123239274318759046526327095178406267264828893646896593219169521106361729757074376148061601331
1049116922713186094041450148428664236347169828924181804843652305388645598098392738364906854808230142678031
4393744043180782267877949400620648915124895251654300563444837504675175420704331337248687063323756164523236
0481932024377596890914783372179553676992603235715185513391098402739063753280702313301755754269396202629423
9109453235379101259489649418125636729929670842506675998034562734555985596285122814145825560248417833056452
4050845006598875598751860133586062493278448777200684229659194551653956298296059161004657890721484205486183
0418175604559815168088031783080261445994444677918012432146400983610678683412974872596729258786806223080115
8220262890143644590023016458236667092655712645599257906223047452356255751117707915120027893809757754685461
2101730752279924140702630813779297190946141314580208108773812162453985876969737142588183615260506938092691
7712087321915005831977113322793572385071940612761291872572099404930250277748156614021327434743881966413330
0526342290829064009279449248085561311834401618048013570325078363239389215676431596204426128097009441077761
3063890907129445639405660155924602545420477118614042015523337127050137712103457000957800938926532938572047
8576508777149663403003562380595757191609382171312222810465858388943507176431939973012661591423837170284400
1203994858809962318594724748587765843550770069340992203403787721927283703013808381443941149849717307661629
6134205910501481428394970069595167693904155790285635691105554731268457149744963532055467794077518405666763
7222969090346128706829887104278761090090999160443821794511763620835379716161833124364431267855435550800507
9861246643977241355021282380267267199149897272485129812872836974892764207928686669701772597944078581559093
3250855413129994658111852769165246479081911938423327589769957301209810300917100169571879161694227007952891
5191912521053891838538959315167400505723817401030621004380243011187977704252328073236575129609372456053680
0375165961642361477093303912244097528717320679761281204280267392565573056759315126457500478757565318548258
2141157403047314749251191083561576573200254610968670189030764853137383291268248174118135903282662508254931
3211431478953352317043989053928534946642886074268371824902498092479487226633686823799580875637040808655649
3219054896377855495311673979352707994704523991532975343586905141058640965345141828964744393671828527118435
6079928589597817654395011308884841916351667321369286083095674450280180037371645800916808297270871560918503
8654053436660045504985624687376022557041595800250174095361839287643458003670864954057941720085136357127163
7683234931342307038212744845014405295416953743819454594565331651409909937227228010196546527262278315121034
6768616682613147184361002551786324795015002295369546631773958934413148148583469437452398115995466607120599
7794363440185078360899108948073419633939259318973940943110042116729120199722626609871927014024105805515315
1001098049960441472910394510303126641147267368399733150350367427415469926331652704329406752374490750567395
0892967477911580086439999256481720884742925082154627985607912776861194608621034940553585013447219024454382
4521089284409498132717010673966471114931896789977661595488186193176900175027901783824624387873831483279500
8790264339925770265880058497789846242956603212769458108243481296908409725506710547324713172549971919010395
5330584704072808169315862609388601914768994413767362143208360737513157437631675466647918675389657155510085
0626810005119827486807780592667765654100834778571024250133253391587384761024129794736751001163498977803745
9300254576098706710921535971151782520142812166475430340751286002402970384286159842898166021434298490889173
5968219228446912303590432987723184330991418726467460755831872571313883235601580900959418253020779939764846
2597901883341793830920965841463574411985878296475850943053008148341821747826603773762252997703468752903517
3107920832200380808092121643465868179898105042743753857867891863505177175016065318264069288832501359195171
7853768786588175236642153401096129576307476264807031275736578776235285905715393248457650394439049666808771
1899192498933896524852395536795827530614167131757915756386606004839994179548705868209201195154952031294562
4513154225065748586291616065237966430101726939502822946674896817468211639967949502942840130992359012782504
3742819255763453321757616229275111059836827156722977862005372293231408288705874944406011623652162771755850
3013451471452765841864277071769968435499620257547431811994883385806759692359580622165832464092095350648357
9358177429030183153512900143214955181774569083887193206977696956577717544991499114313689508361606925396064
6989337487094293321918560129910856447025625716350550862068924029758968471428367868473545553358347765253615
6578189996983068654671736445996343136468195427420490472433064675001442697508322369013083895492637066778406
5313286648860801295137717208475811577194910123451417749414827735800414326673323796177169656985827858323005
0526588350224786805064820144457059319734338292386007260169651090325898090991283765227538149352984509941496
6933862815568031306981064525192703818515872648691762563239441425216118427769145067718411735714396681005615
4839524431549448642383842989003998261133224689633465221046925451379692760097196453389553321055842456401874
4861105095911176682894271164005401050377042034605252131822804589299863790357235066510878235004334994239128
5236308896510989246641056331584171142885304143772286629832318970869030400301325951476774237516158840915838
0591516735045191311781939434284829222723040614225820780278291480704267616293025392283210849177599842005951
0531216473181840949313980044407284732590260916973099815385393903128087882390294800157900800000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000

Wow, the ouput is massive!!!

The same program using Java Swing is as follows...

Code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import javax.swing.*;

// Big Numbers Factorial
public class FactorialBig extends JFrame {

    private JTextField textField = new JTextField(23);
    private JTextArea textArea = new JTextArea();
    private JButton process = new JButton("Process");
    private Font font = new Font("Dialog", Font.BOLD, 15);
    private int number = 0;
    private String output = "";
    private String outputScientific = "";
    private JCheckBox scientific = new JCheckBox("Scientific");

    public FactorialBig() {

        // Nimbus look'n feel
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) {
            // Do nothing
        }
        // update the UI
        textField.updateUI();
        textArea.updateUI();
        process.updateUI();
        scientific.updateUI();

        // Set the font
        textField.setFont(font);
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setEditable(false);
        JPanel top = new JPanel(new FlowLayout(FlowLayout.CENTER));
        top.add(new JLabel("Enter a Number : "));
        top.add(textField);
        top.add(scientific);
        top.add(process);
        add(top, BorderLayout.NORTH);

        scientific.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (scientific.isSelected()) {
                    textArea.setText(outputScientific);
                } else {
                    textArea.setText(output);
                }
            }
        });

        process.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                textArea.setText("");

                String input = textField.getText();
                // The user has not entered anything
                if (input.equals("")) {
                    JOptionPane.showMessageDialog(null, "Sorry no input!!");
                } else {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            setCursor(new Cursor(Cursor.WAIT_CURSOR));
                            process.setEnabled(false);
                            try {
                                number = Integer.parseInt(textField.getText());
                                output = "" + factorial(number);
                                outputScientific = toScientific(output);
                                if (scientific.isSelected()) {
                                    textArea.setText(outputScientific);
                                } else {
                                    textArea.setText(output);
                                }

                            } catch (NumberFormatException nfe) {
                                JOptionPane.showMessageDialog(null, "OOps not a valid number !!!");
                                textField.setText("");
                                textArea.setText("");
                                process.setEnabled(true);
                                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                            }
                            process.setEnabled(true);
                            //Scroll to the bottom of the textArea
                            textArea.setCaretPosition(textArea.getDocument().getLength());
                            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                        }
                    }).start();
                }
            }
        });

        add(new JScrollPane(textArea), BorderLayout.CENTER);

        setSize(800, 600);
        setTitle("FactorialDemo");
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private String toScientific(String str) {
        if (str.length() > 12) {
            String firstDigit = str.substring(0, 1);
            String restDigit = str.substring(1, 30);
            return firstDigit + "." + restDigit + "e+" + (str.length() - 1);
        }
        return str;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FactorialBig();
            }
        });
    }

    private BigInteger factorial(int fact) {
        BigInteger m = new BigInteger("1");
        for (int i = 1; i <= fact; i++) {
            m = m.multiply(new BigInteger("" + i));
        }
        return m;
    }
}

*s12.postimg.org/l6mf0zwe1/Factorial_Big.png


Enter a number & press the 'Process' button. If you want the scientific notation select the scientific checkbox.


Q) Write a program to zoom a given image to 25%, 50%, 100%, 150%, 200% and so on ?



Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/20/14
 * Time: 1:20 PM
 * To change this template use File | Settings | File Templates.
 */
public class ImageZoomCombo extends JFrame {

    private final String []zFactor = new String[] {"10%", "25%", "50%", "75%", "100%", "125%", "150%", "200%", "250%", "300%", "450%", "500%", "600%", "700%", "800%"};
    private final JComboBox <String> comboBox = new JComboBox<>(zFactor);
    private Image image;
    private final JLabel label = new JLabel();
    private int imgWidth, imgHeight;

    public ImageZoomCombo() {
        //Set System look'n feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            System.err.println("Error loading look 'n feel!!");
        }
        comboBox.updateUI();
        // Alignment for the Label
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);
        comboBox.setPreferredSize(new Dimension(150, 30));
        comboBox.setSelectedItem("100%");
        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // Catch the OutOfMemoryError error, in case it happens!!
                        try
                        {
                            String zoomFactor = comboBox.getSelectedItem().toString();
                            //Remove the percent (%) sign from the String
                            zoomFactor = zoomFactor.substring(0, zoomFactor.lastIndexOf("%"));
                            int zoomValue = 100;
                            try
                            {
                                zoomValue = Integer.parseInt(zoomFactor);
                            }  catch (NumberFormatException nfe) {
                                zoomValue = 100;
                            }
                            setCursor(new Cursor(Cursor.WAIT_CURSOR));
                            label.setIcon(new ImageIcon(image.getScaledInstance(imgWidth * zoomValue/100, imgHeight * zoomValue/100, Image.SCALE_SMOOTH)));
                            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                        }  catch (OutOfMemoryError ome) {
                            JOptionPane.showMessageDialog(null, "Oops, The JVM is running out of Memory (Heap)!! \n Start the JVM with -Xms128m -Xmx256m argument", "Error", JOptionPane.ERROR_MESSAGE);
                            System.exit(-1);
                        }
                    }
                }).start();
            }
        });

        //Get the Image
        image = getImage("Images/Andrea Mantea3.jpg");
        if(image != null) {
            imgWidth = image.getWidth(this);
            imgHeight = image.getHeight(this);
            label.setIcon(new ImageIcon(image));
        }
        add(new JScrollPane(label));
        JPanel top = new JPanel(new FlowLayout(FlowLayout.CENTER));
        top.add(new JLabel("ImageZoom Combo"));
        top.add(comboBox);
        add(top, BorderLayout.NORTH);
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(scrDim.width/2 + 120, scrDim.height);
        setTitle("ImageZoom");
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public BufferedImage getImage(String fileName) {
        try {
            return ImageIO.read(new File(fileName));
        } catch (IOException ioe) {
            System.err.println("Error loading Image : " + fileName + "!!");
            System.exit(-1);
        }
        return null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ImageZoomCombo();
            }
        });
    }
}


*s16.postimg.org/coxbdf1xt/Image_Zoom_Combo.png

Q) Write a program to show a simple calculator in action ?



Code:
//JavaCalculator.java

/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 11/15/14
 * Time: 1:59 PM
 * To change this template use File | Settings | File Templates.
 */
// A Simple Calculator

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

public class JavaCalculator extends JFrame {

    private JLabel label;
    private boolean firstDigit = true;
    private float savedValue = 0.0f; // Initial value
    private String operator = "="; // Initial operator
    private Font font = new Font("Serif", Font.BOLD, 16);

    public JavaCalculator() {
        try
        {
           UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {

        }
        label = new JLabel("0", JLabel.RIGHT);
        label.setFont(font);
        label.setBackground(Color.white);
        add("North", label);
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4));
        addButtons(panel, "789/");
        addButtons(panel, "456*");
        addButtons(panel, "123-");
        addButtons(panel, ".0=+");
        add("Center", panel);
        setSize(250, 200);
        setTitle("Java Calculator");
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public void addButtons(JPanel panel, String labels) {
        int MAX = labels.length();
        JButton []button = new JButton[MAX];
        String text = "";
        for (int i = 0; i < MAX; i++) {
            text = labels.substring(i, i + 1);
            button[i] = new JButton(text);
            button[i].setActionCommand(text);
            button[i].setFont(font);
            button[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {

                    String s = ae.getActionCommand();
                    if ("0123456789.".indexOf(s) != -1) { // isDigit
                        if (firstDigit) {
                            firstDigit = false;
                            label.setText(s);
                        } else {
                            label.setText(label.getText() + s);
                        }
                    } else { // isOperator
                        if (!firstDigit) {
                            compute(label.getText());
                            firstDigit = true;
                        }
                        operator = s;
                    }
                }
            });
            panel.add(button[i]);
        }
    }

    public void compute(String s) {
        float sValue = new Float(s).floatValue();
        char c = operator.charAt(0);
        if(c == '=') {
            savedValue = sValue;
        }
        else if(c == '+') {
            savedValue += sValue;
        }
        else if(c == '-') {
            savedValue -= sValue;
        }
        else if(c == '*') {
            savedValue *= sValue;
        }
        else if(c == '/') {
            savedValue /= sValue;
        }
        label.setText(String.valueOf(savedValue));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JavaCalculator();
            }
        });
    }
}

*s11.postimg.org/io6x3dqjj/Java_Calculator.png



5) Write a program to list the contents of a directory as Icons (Simillar to Windows's View As Icons) ?

Ans) Here is the solution code!!

Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.UIManager.*;
import javax.swing.border.MatteBorder;
import javax.swing.filechooser.FileSystemView;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Sowndar Date: 6/1/15 Time: 3:03 PM To
 * change this template use File | Settings | File Templates.
 */
public class ViewAsIcons extends JFrame {

    private int MAX;
    private JButton[] button;
    private Desktop desktop = Desktop.getDesktop();
    private ImageIcon icon;
    private Image iconImage;
    private MatteBorder matte = new MatteBorder(3, 3, 3, 3, Color.black);
    private ImageIcon dirIcon = null;

    public ViewAsIcons(String dirName) {
        // set the System look 'n feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) {
            // Do nothing
        }
        setLayout(new BorderLayout());
        JPanel panel = new JPanel();
        int cols = 4;
        int rows = MAX / cols;
        panel.setLayout(new GridLayout(rows, cols, 5, 5));
        File directory = new File(dirName);
        if (directory.exists()) {
            //Get the directory contents
            String[] dirList = directory.list();
            File file = null;
            MAX = dirList.length;
            if (MAX > 0) {
                button = new JButton[MAX];
                // Show the directories first, then the files
                Vector <String>fileVector = new Vector<>();
                Vector <String>dirVector = new Vector<>();

                for (int i = 0; i < MAX; i++) {
                    file = new File(dirName + System.getProperty("file.separator") + dirList[i]);
                    if(file.isDirectory()) {
                        dirVector.addElement(file.getName());
                    }
                    else
                    {
                        fileVector.addElement(file.getName());
                    }
                }

                String []tmp = new String[dirVector.size()];
                dirVector.copyInto(tmp);

                String []tmp2 = new String[fileVector.size()];
                fileVector.copyInto(tmp2);

                Vector <String>tmpVector = new Vector<>();
                for (int i = 0; i < tmp.length; i++) {
                    tmpVector.addElement(tmp[i]);
                }
                for (int i = 0; i < tmp2.length; i++) {
                    tmpVector.addElement(tmp2[i]);
                }

                dirList = new String[tmpVector.size()];
                for (int i = 0; i < tmpVector.size(); i++) {
                    dirList[i] = tmpVector.get(i);
                }

                String extension = "";
                for (int i = 0; i < MAX; i++) {
                    file = new File(dirName + System.getProperty("file.separator") + dirList[i]);
                    button[i] = new JButton(dirList[i]);
                    button[i].setVerticalTextPosition(SwingConstants.BOTTOM);
                    button[i].setHorizontalTextPosition(SwingConstants.CENTER);
                    button[i].setActionCommand(file.toString());

                    button[i].addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent ae) {
                            Object source = ae.getSource();
                            for (int j = 0; j < button.length; j++) {
                                button[j].setBorder(null);
                                if(button[j] == source) {
                                    button[j].setBorder(matte);
                                }
                            }
                            try {
                                desktop.open(new File(ae.getActionCommand()));
                            } catch (IOException e) {

                            }
                        }
                    });
                    if (file.isDirectory()) {

                        if(dirIcon == null) {
                            icon = (ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(file);
                            iconImage = icon.getImage();
                            // Scale the Image to thrice its size
                            iconImage = iconImage.getScaledInstance(iconImage.getWidth(null)*3, iconImage.getHeight(null)*3, Image.SCALE_SMOOTH);
                            dirIcon = new ImageIcon(iconImage);
                            button[i].setIcon(dirIcon);
                        }
                        else
                        {
                            button[i].setIcon(dirIcon);
                        }
                        button[i].setToolTipText("Directory");

                    } else {
                        // It's a File
                        extension = file.getName();
                        extension = extension.substring(extension.lastIndexOf(".")+1);
                        button[i].setToolTipText(extension.toUpperCase() + " File");
                        icon = (ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(file);
                        iconImage = icon.getImage();
                        // Scale the Image to twice its size
                        iconImage = iconImage.getScaledInstance(iconImage.getWidth(null)*2, iconImage.getHeight(null)*2, Image.SCALE_SMOOTH);

                        button[i].setIcon(new ImageIcon(iconImage));
                    }

                    button[i].setPreferredSize(new Dimension(150, 90));
                    panel.add(button[i]);
                }
                add(new JScrollPane(panel));
                setSize(800, 600);
                setTitle("ViewAsIcons");
                setVisible(true);
                setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            } else {
                System.out.println("Sorry, No files found!!");
            }
        } else {
            System.out.println("Sorry, the specified directory doesn't exists!!!");
        }
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ViewAsIcons(args[0]);
            }
        });
    }
}

*s11.postimg.org/bojv55wv3/View_As_Icons.png

Here we get the contents of the specified directory using the list() method. We create an array of buttons then finally we add them to a scrollpane.



6) Write a program to list the contents of a directory in a table format?

Ans)

Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.io.File;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 6/1/15
 * Time: 4:13 PM
 * To change this template use File | Settings | File Templates.
 */
public class ViewAsTable extends JFrame {

    private int MAX;
    private String[] columns = {"Name",
            "Date Modified",
            "Type",
            "Size"};
    private Object rows[][];
    private String []readFormat = ImageIO.getReaderFormatNames();

    public ViewAsTable(String dirName) {


        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }
        File directory = new File(dirName);
        if(directory.exists()) {
            String []dirList = directory.list();
            MAX = dirList.length;
            if(MAX > 0) {
                rows = new Object[MAX][4];
                File file = null;
                int fileSize = 0;
                String fileName = "";
                for (int row = 0; row < MAX ; row++) {
                    for (int col = 0; col < 3; col++) {
                        file = new File(dirName + System.getProperty("file.separator") + dirList[row]);
                        rows[row][0] = file.getName();
                        rows[row][1] = new Date(file.lastModified());
                        if(file.isDirectory()) {
                            rows[row][2] = " Directory";
                        }
                        else
                        {
                            if(dirList[row].endsWith("bat")) {
                                fileName = "BATCH File";
                            }
                            else if(dirList[row].endsWith("dll")){
                                fileName = "DLL File";
                            }
                            else if(isImage(dirList[row])){
                                fileName = "Image File";
                            }
                            else if(dirList[row].endsWith("html") || dirList[row].endsWith("htm")) {
                                 fileName = "HTML File";
                            }
                            else if(dirList[row].endsWith("jar")){
                                 fileName = "JAR File";
                            }
                            else if(dirList[row].endsWith("java")) {
                                 fileName = "JAVA File";
                            }
                            else if(dirList[row].endsWith("pdf")) {
                                fileName = "PDF File";
                            }
                            else if(dirList[row].endsWith("mpg") || dirList[row].endsWith("mov") || dirList[row].endsWith("wmv")) {
                                fileName = "Video File";
                            }
                            else if(dirList[row].endsWith("xml")) {
                                fileName = "XML File";
                            }
                            else if(dirList[row].endsWith("zip")) {
                                fileName = "ZIP File";
                            }
                            else if(dirList[row].endsWith("exe")) {
                                fileName = "EXE File";
                            }
                            else if(dirList[row].endsWith("class")) {
                                fileName = "CLASS File";
                            }
                            else {
                                fileName = "File";
                            }

                                rows[row][2] = fileName;
                        }
                        fileSize =  new Integer((int) getSizeInKB(file.length()));
                        if(fileSize < 1) {
                            fileSize = 1;
                        }
                        rows[row][3] = fileSize;
                    }
                }
                TableModel model = new DefaultTableModel(rows, columns) {

                    @Override
                    public Class getColumnClass(int column) {
                        Class returnValue = null;
                        try {
                            if ((column >= 0) && (column < getColumnCount())) {
                                returnValue = getValueAt(0, column).getClass();
                            } else {
                                returnValue = Object.class;
                            }
                            return returnValue;
                        } catch (Exception e) {
                        }
                        return null;
                    }
                };

                add(new JScrollPane(new JTable(model)));
                setSize(800, 600);
                setTitle("ViewAsTable");
                setVisible(true);
                setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            }
            else
                System.out.println("Sorry, No files found!!");
        }
        else
        {
            System.out.println("The specified directory doesn't exist!!!");
            System.exit(-1);
        }

    }

    public boolean isImage(String fileName) {
        for (int i = 0; i < readFormat.length ; i++) {
            if(fileName.endsWith(readFormat[i]))
                return  true;
        }
        return false;
    }

    public double getSizeInKB(long size) {
        //98.3 KB (1,00,756 bytes)
        // 1,00,756 bytes -> 98.3 KB
        // size ? (size*98.3)/100756;
        return (size * 98.3) / 100756;
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ViewAsTable(args[0]);
            }
        });
    }
}

*s12.postimg.org/sozoeoefd/View_As_Table.png

Here we get the contents of the specified directory & convert the array of String to table format. finally add the table to a scrollpane.


15) Write a program to filter out the images in the 'Images' directory & display them as a List (using JList)?
Also selecting an List item should display the corresponding Image. You need to create a directory called 'Images'
under the current directory for this program to run.

Ans)

Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.String;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.ImageIcon;

/**
 * Created with IntelliJ IDEA. User Sowndar Date: 8/1/14 Time: 2:28 PM To change
 * this template use File | Settings | File Templates.
 */
public class ListDemo extends JFrame {

    private String path = "Images/";
    private String[] imgName;
    private JList<String> list = new JList<>();
    private int MAX;
    private JLabel label = new JLabel();
    private ImageIcon icon = new ImageIcon("Icons/image_32x32.png");
    private Dimension scrDim;
    private int width, height;

    //NOTE : You need to create a directory called 'Images' in the current directory and place some JPG or PNG images there
    // atleast 10 or 15 will do!!
    public ListDemo() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) {
            // Do nothing
        }
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        width = scrDim.width;
        height = scrDim.height;

        list.updateUI();
        File directory = new File(path);
        if (!directory.exists()) {
            System.err.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        // Filter out the Images
        imgName = directory.list(new FilenameFilter() {


            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("jpg");
            }
        });
        for (int i = 0; i < imgName.length; i++) {
		     // Discard the file extension
		     imgName[i] = imgName[i].substring(0, imgName[i].lastIndexOf("."));
        }
        MAX = imgName.length;

        if (MAX == 0) {
            System.err.println("OOps , No Images found!!");
            System.exit(-1);
        }
        //set the List data items
        list.setListData(imgName);
        //Select more than 1 item use the SHIFT key (hold it)!!
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setCellRenderer(new ImageRenderer());

        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(list), label);
        splitPane.setDividerLocation(350);
        splitPane.setOneTouchExpandable(true);
        // Listen for Mouse events
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String selected = list.getSelectedValue();
                label.setIcon(new ImageIcon(getImage(path + selected + ".jpg")));
            }
        });

        add(splitPane);
        setTitle("ListDemo");
        setSize(width, height);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    //Get the Image
    public Image getImage(String fileName) {
            try {
                return ImageIO.read(new File(fileName));
            } catch (IOException ioe) {
                System.err.println("Error loading Image : " + fileName);
            }

        return null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ListDemo();
            }
        });
    }

    //  Inner class  for rendering icon for the List
    class ImageRenderer extends JLabel implements ListCellRenderer<Object> {

        Dimension dim = new Dimension(210, 74);

        ImageRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            //  If this is the selection value request from a combo box
            //  then find out the current selected index from the list.
            if (index == -1) {
                int selected = list.getSelectedIndex();
                if (selected == -1) {
                    return this;
                } else {
                    index = selected;
                }
            }
            setText(value.toString());
            try {
                if (icon != null) {
                    setIcon(icon);
                }

            } catch (Exception e) {
            }
            setPreferredSize(dim);
            setFont(list.getFont());
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            return this;
        }
    }
}

*s4.postimg.org/i0kyj3s4p/List_Demo.png

The program filters the images in the 'Images' directory. We create a List using the found values. Clicking on a list item displays the corresponding image.


16) Write a program to filter the images in the 'Images' directory & display them using a JComboBox. Also create next & previous
button, to display the next & previous image.You need to create a directory called 'Images'
under the current directory for this program to run.

Ans)

Code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 * Created with IntelliJ IDEA. User Sowndar Date: 8/1/14 Time: 2:28 PM To change
 * this template use File | Settings | File Templates.
 */
public class ComboBoxDemo extends JFrame implements ActionListener {

    private String path = "Images/";
    private String[] imgName;
    private JComboBox<String> comboBox;
    private int MAX;
    private JLabel label = new JLabel();
    private ImageIcon icon = new ImageIcon("Icons/image_32x32.png");
    private JButton back;
    private JButton forward;
    private int index = 0;

    public ComboBoxDemo() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) {
            // Do nothing
        }

        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);
        File directory = new File(path);
        if (!directory.exists()) {
            System.err.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        // Filter out the Images
        imgName = directory.list(new FilenameFilter() {
            String[] readFormat = ImageIO.getReaderFormatNames();

            @Override
            public boolean accept(File dir, String name) {
                for (int i = 0; i < readFormat.length; i++) {
                    if (name.endsWith(readFormat[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        back = new JButton(new ImageIcon("resources/back.png"));
        forward = new JButton(new ImageIcon("resources/forward.png"));
        back.setToolTipText("Previous");
        back.setBorderPainted(false);
        back.setContentAreaFilled(false);
        forward.setToolTipText("Next");
        forward.setBorderPainted(false);
        forward.setContentAreaFilled(false);
        // Add the listeners to the buttons
        back.addActionListener(this);
        forward.addActionListener(this);

        MAX = imgName.length;

        if (MAX == 0) {
            System.err.println("OOps , No Images found!!");
            System.exit(-1);
        }
        comboBox = new JComboBox<>(imgName);
        JPanel top = new JPanel(new FlowLayout(FlowLayout.CENTER));
        top.add(new JLabel("Select a Image: "));
        top.add(comboBox);
        add(top, BorderLayout.NORTH);
        add(new JScrollPane(label), BorderLayout.CENTER);
        comboBox.setRenderer(new ImageRenderer());
        comboBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                String selected = comboBox.getSelectedItem().toString();
                label.setIcon(new ImageIcon(path + "/" + selected));
            }
        });
        JPanel bottom = new JPanel(new FlowLayout(FlowLayout.CENTER, 150, 5));
        bottom.add(back);
        bottom.add(forward);
        add(bottom, BorderLayout.SOUTH);
        //Show the first Image
        label.setIcon(new ImageIcon(path + "/" + imgName[0]));
        setTitle("ComboBoxDemo");
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(scrDim.width / 2 + 150, scrDim.height);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == back) {
            index = comboBox.getSelectedIndex();
            if (index <= 0) {
                index = imgName.length;
            }
            index--;
            comboBox.setSelectedIndex(index);
        } else if (source == forward) {
            index = comboBox.getSelectedIndex();
            index++;
            if (index >= imgName.length) {
                index = 0;
            }
            comboBox.setSelectedIndex(index);
        }
    }

    //Get the Image
    public Image getImage(String fileName) {
        try {
            return ImageIO.read(new File(fileName));
        } catch (IOException ioe) {
            System.err.println("Error loading Image : " + fileName);
        }
        return null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ComboBoxDemo();
            }
        });
    }

    //  Inner class  for Image preview for the comboBox
    class ImageRenderer extends JLabel implements ListCellRenderer<Object> {

        Dimension dim = new Dimension(210, 74);

        ImageRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            //  If this is the selection value request from a combo box
            //  then find out the current selected index from the list.
            if (index == -1) {
                int selected = list.getSelectedIndex();
                if (selected == -1) {
                    return this;
                } else {
                    index = selected;
                }
            }
            setText(value.toString());
            try {
                if (icon != null) {
                    setIcon(icon);
                }

            } catch (Exception e) {
            }
            setPreferredSize(dim);
            setFont(list.getFont());
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            return this;
        }
    }
}

*s16.postimg.org/w21y1g3td/Combo_Box_Demo.png

Here we filter the images in the 'Images' directory create a ComboBox using these values. Selecting a particular item in the combobox displays the particular image.
The back & forward buttons displays the previous image & the next image in the array.

Q) Write a program display Polygons with red color and another one with blue & red patterns?

Code:
/**
 *
 * @author Sowndar
 */
import java.awt.*;
import javax.swing.*;

class PolygonDemo extends JComponent {

    private Polygon p;
    private Polygon pBase;
    private int step = 10;

    public PolygonDemo() {
        pBase = new Polygon();
        pBase.addPoint(0, 0);
        pBase.addPoint(10, 0);
        pBase.addPoint(5, 15);
        pBase.addPoint(10, 20);
        pBase.addPoint(5, 20);
        pBase.addPoint(0, 10);
        pBase.addPoint(0, 0);
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height));
    }

    void scalePolygon(float w, float h) {
        p = new Polygon();
        for (int i = 0; i < pBase.npoints; ++i) {
            p.addPoint((int) (pBase.xpoints[i] * w),
                    (int) (pBase.ypoints[i] * h));
        }

    }

    void draw(Graphics2D g, int x, int y, int w, int h) {
        Graphics ng = g.create();
        try {
            ng.translate(x, y);
            scalePolygon(((float) w / 10f), ((float) h / 20f));
            ng.drawPolygon(p);
        } finally {
            ng.dispose();
        }
    }

    void fill(Graphics2D g, int x, int y, int w, int h) {
        Graphics ng = g.create();
        try {
            ng.translate(x, y);
            scalePolygon(((float) w / 10f), ((float) h / 20f));
            ng.fillPolygon(p);
        } finally {
            ng.dispose();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        // Set RenderingHints properties
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

        Rectangle bounds = getBounds();

        int cx, cy, cw, ch;

        Color color;

        for (color = Color.red, cx = bounds.x, cy = bounds.y, cw = bounds.width / 2, ch = bounds.height;
                cw > 0 && ch > 0;
                cx += step, cy += step, cw -= (step * 2), ch -= (step * 2), color = darker(color, 0.9)) {
            g2d.setColor(color);
            draw(g2d, cx, cy, cw, ch);
        }

        for (cx = bounds.x + bounds.width / 2, cy = bounds.y, cw = bounds.width / 2, ch = bounds.height;
                cw > 0 && ch > 0;
                cx += step, cy += step, cw -= (step * 2), ch -= (step * 2)) {
            if (g2d.getColor() == Color.red) {
                g2d.setColor(Color.blue);
            } else {
                g2d.setColor(Color.red);
            }

            fill(g2d, cx, cy, cw, ch);
        }
    }

    static Color brighter(Color c, double factor) {
        return new Color(Math.min((int) (c.getRed() * (1 / factor)), 255),
                Math.min((int) (c.getGreen() * (1 / factor)), 255),
                Math.min((int) (c.getBlue() * (1 / factor)), 255));
    }

    static Color darker(Color c, double factor) {
        return new Color(Math.max((int) (c.getRed() * factor), 0),
                Math.max((int) (c.getGreen() * factor), 0),
                Math.max((int) (c.getBlue() * factor), 0));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame("PolygonDemo");
                f.add(new PolygonDemo());
                f.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                f.setVisible(true);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}


*s13.postimg.org/6q569k83n/Polygon_Demo.png


This wraps up Java programming foundation!!
I hope that you liked it!! As you write more programs, solve more problems, you will be able
to master the Java programming language. Happy programming!!


Here are some books for Java programming at the introductory level.

Introductory Books for Java programming

1) Head First Java - Introductory book for Java programming

2) Thinking in Java by Bruce Eckel - Understand the core concepts of Java programming

3) Data-Structures & Algorithms in Java by Robert Lafore - Understand algorithms & data-structures

4) Beginning Java Objects (Wrox) - Understand OOPS methodology

5) Object-Oriented Programming in Java by Balagurusamy

6) Big Java Late Objects by Cay S. Horstmann (Discusses OOPS methodology)

7) Java How To Program by H M Deitel & P J Deitel (Contains many exercises, learn programming from a Java champion)

8) Object-Oriented Programming in Java by Stephen Gilbert and Bill McCarty

9) Algorithms in Java 4th edition by Robert SedgeWick (Understand algorithms & data-structures)

10) Core Java - Vol - I & II by Horstmann C S (Understand the core Java topics)
 
Top Bottom