# The Ultimate Guide to Java Programming & Reference:



## JGuru (Jul 24, 2013)

[size=+2]The Ultimate Guide to Java Programming & Reference[/size]

Hey Guys in this post, I'm going to give you the list of the best books & resources on the Web to study Java Programming, plus I'm going to give you
 some programs written by me to help you understand Java programming better.

 I have more than 15 years experience programming in Java. I have written tons of programs from Image processing, accounting , e-commerce,
 database management, Media player, photo browser, File Manager, Dictionary, Web Server , charting tool, Compiler design , Java IDE (Integrated Development Environment)etc., 
 I have expert knowledge in C/C++/C#, Java, HTML , JavaScript, AJAX, Oracle, XML etc., 

 I'm going to share my experience & deep understanding of Java programming. 

 I'm a Sun Certified Java Programmer, Sun Certified Java Developer, Sun certified Java Architect.

 I have also passed Oracle Certified Professional, Java SE 7 Programmer exam last year.

*Java Terminology*


```
[b]AWT[/b] : AWT is a package of classes for creating components such as buttons, menus, and scrollbars for applets and standalone applications.
      
      [b]Applet[/b] : An applet is a Java program that runs within the web browser. Applets use a graphical user interface and may have text, images, buttons, scrollbars, and sound. 
      
      [b]Java Advanced Imaging[/b] (JAI) : The JAI API provides a set of object-oriented interfaces that support a simple, high-level programming model
      which lets you manipulate images easily, and JAI broadens the reach of the Java platform to allow sophisticated, high performance image processing
      functionality to be incorporated into Java applets and applications.
      
      [b]Java API for XML Processing (JAXP)[/b] : JAXP enables applications to parse validate and transform XML documents. The latest release is JAXP 1.3, which is part of J2SE 5.0. An implementation that works for earlier versions of J2SE is also available.
      
      [b]Java Authentication and Authorization Services (JAAS)[/b]: JAAS is a set of APIs that enable services to authenticate and enforce access controls upon users. It implements a Java technology version of the standard Pluggable Authentication Module (PAM) framework, and supports user-based authorization.
      
      [b]Java Communications API[/b] : The Java Communications API can be used to write platform-independent communications applications for technologies such as voice mail, fax, and smart cards. 
      
      [b]Java Cryptography Extension (JCE)[/b] : JCE is a set of packages that provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.
      
      [b]Java Foundation Classes (JFC)[/b] : JFC are a set of GUI components and other services simplifying the development and deployment of desktop and Internet/Intranet applications. The JFC are a superset that contains AWT. JFC extends AWT by adding many components and services. JFC consists of Swing, Java 2D, AWT, Accessibility, and the Drag-and-Drop APIs.
      
      [b]Java Media FrameWork (JMF)[/b]: JMF enables audio, video and other time-based media to be added to applications and applets built on Java technology. This optional package, which can capture, playback, stream, and transcode multiple media formats, extends the Java platform for multimedia developers by providing a powerful toolkit to develop scalable, cross-platform technology.
      
      [b]Java Native Interface (JNI)[/b]: JNI is the native programming interface for Java that is part of the JDK. The JNI allows Java code to operate with applications and libraries written in other languages, such as C, C++, and assembly. Recommended only for advanced programmers.
      
      [b]Java 2 Platform, Enterprise Edition (JavaEE)[/b] : The JavaEE platform provides a component-based approach to the design, development, assembly, and deployment of enterprise applications. The J2EE platform gives you a multitiered distributed application model, the ability to reuse components, a unified security model, and flexible transaction control.
      
      [b]Java 2 Platform, Micro Edition (JavaME)[/b]: J2ME is targeted for the consumer and embedded market. The API specifications are based on J2SE, but modified to meet the unique requirements of each product. J2ME makes it possible to write Java applications for cell phones, smart cards, pagers, and other consumer devices.
      
      [b]Java 2 Platform, Standard Edition (JavaSE)[/b] : Java SE includes the essential compiler, tools, runtimes, and APIs for writing, deploying, and running applets and applications in the Java programming language.
      
      [b]Java 3D API[/b] : The Java 3D API provides a set of object-oriented interfaces that support a simple, high-level programming model you can use to build, render, and control the behavior of 3D objects and visual environments. With the Java 3D API, you can incorporate high-quality, scalable, platform-independent 3D graphics into applications and applets based on Java technology.
      
      [b]Java Virtual Machine (JVM)[/b]: The JVM executes instructions that a Java compiler generates. This runtime environment, or JVM, is embedded in various products, such as web browsers, servers, and operating systems.
      
      [b]Java Web Start[/b] : Using Java Web Start technology, standalone Java software applications can be deployed with a single click over the network. Java Web Start ensures the most current version of the application will be deployed, as well as the correct version of the Java Runtime Environment (JRE).
      
      [b]JavaBeans[/b] : JavaBeans architecture provides a way of designing reusable software components, that can be visually manipulated in builder tools. JavaBeans can be simple like buttons, or more complex like a tool to access databases.
      
      [b]JavaHelp System[/b] : JavaHelp software is a full-featured, platform-independent, extensible help system that enables you to incorporate online help in applets, components, applications, operating systems, and devices. Authors can also use the JavaHelp software to deliver online documentation for the Web and corporate intranet.
      
      [b]JavaServer Faces Technology[/b] : JavaServer Faces technology simplifies building user interfaces for JavaServer applications. Developers of various skill levels can quickly build web applications by assembling reusable UI components in a page, connecting these components to an application data source, and wiring client-generated events to server-side event handlers. 
      
      [b]JavaServer Pages (JSP)[/b] : Create dynamic web pages with JSP pages by embedding scriptlets (Java programming language code) with HTML. JSP pages process forms, perform calculations, or do anything else that can be written with the Java programming language.
      
      [b]JDBC[/b] : JDBC is a Java API for executing SQL statements. By using the JDBC API, you can access almost any data source, from relational databases to spreadsheets to flat files. J2SE includes the JDBC API.
      
      [b]JINI[/b] : The Jini network technology enables any service--from enterprise systems to kitchen appliances--to network smoothly and simply. The Jini architecture lets each service (device or software) tell others how to talk to it, without any administrator settings.
      
      [b]RMI[/b] : RMI lets Java applications communicate across a network. The communicating applications can be running on different computers on opposite sides of the planet. This higher-level and method-based approach to network communications allows access to a remote object as easily as a local object.
      
      [b]Servlets[/b] : A servlet is an extension to a server that enhances the server's functionality. Servlets are most commonly used to process forms, handle redirects or authenticate user names and passwords, and create dynamic content.
```
 

 We are the list of best books I have short-listed for Programming better. You should also write more programs yourself to become a better programmer!!
 The real onus is on your part!!

*Java Biblography:*

*Java Standard Edition*

 1) Head First Java ( For people who don't have any knowledge of programming, text is simple to understand & learn)  

 2) Core Java - Vol -I & II by Horstmann C S (Very well written book covers the basics & intermediate topics)

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

 4) Beginning Java Objects (Wrox) - A good introduction to OOPS methodology.

 4) Java Tutorial (The Java™ Tutorials) (Discusses fundamentals, intermediate & advanced topics like RMI, image processing, printing etc., )

 5) JFC Swing Tutorial - A Guide to Constructing GUIs (2nd, 04) by Walrath, Kathy - Campione, Mary - Huml, Alison (Excellent tutorial of JFC!!!)

 6) Java 2 Developers Handbook by Philip Heller & Siomn Roberts ( Covers Advanced Java topics - crptography, custom layout managers, RMI, protocol handlers etc.,)

 7) Data Structures & Algorithms in Java by Robert Lafore (Covers data structures & algorithms that are the backbone in any language)

 8) Algorithms in Java (4th Edition) by Robert Sedgewick and Kevin Wayne (Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne)

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

 10) Effective Java by Joshua Bloch  (Must read book for a Java developer)

 11) Professional Java Programming (Wrox)

 12) The Java FAQ (The Java Series) by Jonni Kanerva  (Discusses nitty-grity things like Class, interface, applets, networking, etc.,)
       Very helpful to answer interview questions.

 13) Java Class Libraries by Patrick Chan (Gives a detailed examples of the Java API Classes)

 14) Complete Java2 Certification Study Guide by Philip Heller and Simon Roberts (Excellent certification study guide)

 15) Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805-A Comprehensive OCPJP 7 Certification... by SG Ganesh and Tushar Sharma 

 16) OCA Java SE 7 Programmer I Study Guide (Exam 1Z0-803) (Oracle Press) by Edward G. Finegan and Robert Liguori

 17) The Java Developers Almanac 1.4, Volume 1: Examples and Quick Reference (4th Edition) by Patrick Chan 

 18) Java Developers Almanac 1.4, Volume 2 - Examples & Quick Reference (03) by Chan, Patrick (Java Developer's Almanac is very exhaustive , covers lot of topics like JavaSound, JavaBeans, printing, charts, image processing, etc.,
       It's a must read for a serious Java Developer.)

 19) Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea (How to program Java for multi-core Processors using the new java.util.concurrent, java.util.concurrent.atomic
   java.util.concurrent.locks packages)

 20) Java Swing 5th Edition by Eckstein (Oreilly) (Discusses JFC in detail with many useful programs)

 21) Java NIO (Oreilly) (Discusses Java NIO in detail)

 22) Killer Game Programming in Java by Andrew Davison(Java3D game programming in detail)

 23) Desktop Java Live (Discusses various Layout Managers , GUI Builders, Swing Threading, Data Binding , Validation, Packaging & Deployment )

 24) Practical Artificial Intelligence Programming in Java 3rd Edition Mark Watson  (discusses AI programming in depth using Java language)

 25) Mac OS X for Java Geeks (Discusses Apple's Quicktime for Java examples + others)

 26) Thinking in Java (Contains examples & numerous exercises )

 27) Introduction to Compiler Construction in a Java (Hardcover) by Bill Campbell (Author) , Swami Iyer (Author) , Bahar Akbal-Delibas  (Discusses Compiler design)

 28) Java 3D Programming by Daniel Selman (Java 3D Programming steps programmers through the important design and implementation phases of developing a successful Java 3D application.)

 29) Beginning Java Networking (Wrox) (Discusses Java network programming in detail)

 30) iText in Action (Discuss PDF Reader, Writer, Tables, Images etc.,)

 31) Java 2D API Graphics by Vincent Hardy (Discusses Java2D, Image processing etc., in depth)

 32) Image processing in Java

 33) The Complete Guide to Java Database Programming by Siple 

 34) JDBC Database Access with Java : A Tutorial & Annotated Reference 

 35) Java : Application Programming Interface Volume I by the Java team

 36) The Java Application Programming Interface Volume II - James Gosling & the Java team

 37) The Java Programming Language by James Gosling & Ken Arnold (Addison Wesley 1996)

 38) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty

 39) Oracle 11g: JDBC Programming by Price

 40) Software Engineering in Java

 41) Java Internationalization (Oreilly)

 42) Java Native Methods

 43) Beginning Java Databases (Wrox)

 44) Professional Java Databases (Wrox)

 45) Java Threads (Oreilly)

 46) Professional Java XML Programming by Myers (Wrox)

 47) Professional Java Server Programming (Wrox)

 48) Professional Java Networking (Wrox)

 49) Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and Jeff Kramer. (An introduction to concurrent programming through a combination of modeling and practical examples.)

 50) Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea. (A comprehensive work by a leading expert, who's also the architect of the Java platform's concurrency framework.)

 51) Oracle Database JDBC Developer's Guide & Reference

 52) Java 1.7 Class Libraries Unleashed 

 53) Mastering Java 2 by John Zukowski (Sybex/BPB Publications)

 54) Pro ORACLE JDBC PROGRAMMING- R.M.MENON (apress publishers)

 55) JAVA 2 Networking by Pistoria

 56) Java Security by Scott oaks

 57) Mastering Java Security 

 58) Java Cryptography 

 59) John Zukowski's Definitive Guide to Swing

 60) Graphic Java 2 : Volume 2 Swing , Mastering the JFC by David M Geary

 61) JDBC API : Tutorial & Reference by Fisher, Ellis, Bruce

 62) Building Imaging applications with Java technology : Using AWT imaging, Java2D and Java Advanced Imaging by Lawrence H Rodrigues

 63) The Art of Image Processing with Java by Kenny A Hunt

 64) Essential Java 3D fast : Developing 3D Graphics applications in Java by Ian Palmer

 65) Java RMI by William Grosso (Oreilly)

 66) An Itroduction to Network Programming with Java : Java 7 Compatible by Jan Graba

 67) Java Database Programming Bible by John O' Donahue

 68) Java Programming (Oracle Press)by Poornachandra Sarang

 69) Distributed Java 2 Platform Database Development (Sun MicroSystem Press) by Stewart Birnam

 70) Expert Oracle JDBC Programming: High Performance Applications with Oracle 10g (Oaktable Press) by R M Menon

 71) Image Processing with ImageJ by Jose Maria Mateos and Javier Pascau


*Java Enterpise Edition*

  1) The Java EE 6 Tutorial: Basic Concepts (Java Series) by Eric Jendrock, Ian Evans, Devika Gollapudi and Kim Haase

  2) Mastering Enterprise JavaBeans and the Java 2 Platform, Enterprise Edition by Ed Roman, Rima Patel, Sriganesh, Gerald Brose  

  3) JSP 2.0 : The Complete Reference by Phil Hanna

  4) Java Servlet Programming by William Crawford and Jason Hunter (Oreilly)

  5) Java Server and Servlets: Building portable web applications by Peter Rossbach (Author), Hendrik Schreiber

  6) Struts : The Complete Reference

  7)  Advanced Programming for the Java 2 Platform by Calvin Austin and Monica Pawlan (Discusses Swing , Applets, JNI, distributed computing, )

  8) Java Server Pages Developers Handbook by Nick Todd & Mark Szolkowski 

  9) BEA WebLogic Platform 10 Jatinder Prem (Sams)

  10) BEA WebLogic Server 10 Unleashed (Sams)

  11) JFC Unleashed (Discusses JFC in depth)

  12) Java RMI (distributed computing in Java)

  13) J2EE : The Complete Reference (Tata McGrawHill)

  14) Java CORBA Client Server Programming

  15) IBM Websphere Application Server programming

  16) Oracle 11g :  JDeveloper Handbook by Koletzke

  17) Oracle 11g: Application Server portal Handbook

  18) Oracle 11g: Java Component Programming with EJB, CORBA & JSP

  19) J2EE Bible by Jamie Jaworsky  (Techmedia)

  20) Head First EJB by Sierra Bates


*Java Micro Edition*

  1) J2ME : The Complete Reference


*Other Titles in Programming + Others*

  1) Oracle Database 11g : The Complete Reference (Tata McGrawHill)

  2) MySQL : The Complete Reference (Tata McGrawHill)

  3) The Object Primer : The Application Developer's Guide to Object-Orientation by Scott W Ambler (Sigs Books 1995)

  4) Object-Oriented Analysis and Design iwth Applications by Grady Booch (Addison Weslry 1994)

  5) The Mythical Man-Month by Frederick P Brooks Jr (Addison Wesley 1975) 

  6) An Introduction to Object-Oriented Programming by Timothy Budd (Addison Wesley 1996)

  7) Object-Oriented Design Heuristics by Arthur J Riel (Addison Wesley)

  8) Programming Pearls by Jon Bentely (Addison Wesley 1986)

  9) Writing Solid Code by Steve Maguire (Microsoft Press 1993)

  10) The Art of Computer Programming by Donald E. Knuth (3 Volumes ,Addison Wesley 1997) for a serious researcher (PhD) in the field of Computer Science. This work is highly mathematical.

  11) Algorithms in C++ by Robert Sedgewick (Addison Wesley 1992)

  12) Regular Expressions (Oreilly)

  13) Mastering Regular Expressions by Jeffrey E. F. Friedl

  14) C++ FAQs by Cline & Tomov

  15) Head First C#, 2E: A Learner's Guide to Real-World Programming with Visual C# and .NET by Andrew Stellman and Jennifer Greene

  16) Beginning Visual C# 2012 Programming by Karli Watson, Jacob Vibe Hammer, Jon Reid and Morgan Skinner 

  17) Visual C# 2012 How to Program (5th Edition) (How to Program (Deitel)) by Paul Deitel and Harvey Deitel 

  18) C# Design Pattern Essentials by Tony Bevis

  19) Professional C# 2012 and .NET 4.5 by Christian Nagel, Bill Evjen, Jay Glynn and Karli Watson 

  20) Beginning ASP.NET 4.5: in C# and VB by Imar Spaanjaars

  21) Professional ASP.NET 4.5 in C# and VB by Jason N. Gaylord, Christian Wenz, Pranav Rastogi, Todd Miranda, Scott Hanselman

  22) Professional ASP.NET MVC 4 by Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen

  23) ASP.NET 3.5 Website Programming Problem - Design - Solution by Chris Love, Marco Bellinaso

  24) SQL Server : The Complete Reference

  25) Mastering XML (BPB)

  26) Mastering HTML (BPB)

  27) Mastering JavaScript & JScript (Sybex/ BPB)

  28) Oracle 11g: DBA Handbook by Kevin Loney

  29) ASP.NET Unleashed 

  30) Introduction to Relational Databases and SQL Programming

  31) Adobe PhotoShop CS5 Bible (Wiley Publishing)

  32) C++ : The Programming Language by Bjarne Stroustrup

  33) Annotated C++ Reference Manual by Ellis & Stroutstrup (Contains nitty gritty details suitable for experienced C++ programmers)

  34) Visual C++.NET Bible

  35) Visual Basic.NET Bible

  36) Visual C#.NET Bible

  37) ASP.NET Bible

  38) Object-oriented Programming in C++ by Robert Lafore (Waite Group, 1995)

  39) C: The Complete Reference by Herbert Schildst

  40) C++ : The Complete Reference  by Herbert Schildst

  41) Algorithms in C by Robert Sedgewick (Addison Wesley)

  42) Advanced PL/SQL Programming  (Oracle press)

  43) Image Processing in C++ 

  44) Algorithms in C++ by Robert Sedgewick (Addison Wesley)

  45) AJAX Bible

  46) RedHat Linux Bible

  47) Ubuntu Linux Bible

  48) Beginning Linux Programming 2nd Edition Matthew

  49) Ivor Horton's Beginning C++ - The Complete Language

  50) Professional Active Server Pages (Wrox)

  51) Professional MFC with Visual C++ (Wrox)

  52) Professional PHP Programming (Wrox)

  53) Professional XML (Wrox)

  54) Professional JavaScript (Wrox)

  55) Internet Core Protocols : The Definitive Guide by Hall (Oreilly)

  56) Oracle 11g Instant PL/SQL Scripts by Kevin Loney

  57) Oracle 11g Performance Tuning Tips & Techniques 

  58) Computer Desktop Encyclopedia 10/e by Freedman

  59) C Pearls by Yeshwant Kanetkar

  60) Design Patterns: Elements of Reusable Object-Oriented Software , by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional Computing Series, 1994).

  61) Visual Studio 2014 Bible

  62) Dreamweaver Bible

  63) Maya Bible

  64) 3DS Bible

  65) Deep C by S G Ganesh

  66) Office 2014 Bible

  67) The Unified Software Development Process by Ivar Jacobson, Grady Booch and James Rumbaugh

  68) Software Engineering: A Practioners Approach”, 5th Edition by Roger S.Pressman (2002), Tata MCGraw-Hill.

  69) ORACLE DATABASE 11g  PL/SQL 101 by  Christopher Allen   (Oracle press)

  70) Professional Oracle  Programming- RICK GREENWALD ,ROBERT STACKOWIAK  ,  GARY DODGE ,  DAVID KLEIN,  BEN SHAPIRO ,CHRISTOPHER G CHELLIAH (Wiley publishers)

  71) Database System Concepts - ABRAHAM SILBERSCHATZ, HENRY.F.KORTH, S. SUDARSAN

  72) Oracle Database 12c PL/SQL Programming

  73) C Programming language by Brian Kenighan & Dennis Ritchie

  Most of the Addison Wesley book prints are available from Pearson Education (Economy edition), Checkout the complete books of Oracle Press, Microsoft Press, Addison Wesley. 
  All are excellent books.

  The JDK software is available from Oracle | Hardware and Software, Engineered to Work Together. The Java 7 Documentation is available at Java Platform SE 7
   Alternatively, you can download the Java 7 Documentation from Unauthorized Request 

  Use a good download manager like FlashGet to download.

*PATH and CLASSPATH*

  Update the PATH Environment Variable (Microsoft Windows)

  You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.

  Set the PATH environment variable if you want to be able to conveniently run the executables (javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

*C:\Program Files\Java\jdk1.7.0\bin\javac MyClass.java*

  The PATH environment variable is a series of directories separated by semicolons (. Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.

  The following is an example of a PATH environment variable:

*C:\Program Files\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem*

  It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:


```
Windows XP
  
      Select Start, select Control Panel. double click 'System', and select the 'Advanced tab'.
      Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
      In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
  
  Windows Vista:
  
      From the desktop, right click the My Computer icon.
      Choose 'Properties' from the context menu.
      Click the Advanced tab (Advanced system settings link in Vista).
      Click 'Environment Variables'. In the section 'System Variables', find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
      In the Edit 'System Variable' (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
  
  Windows 7:
  
      From the desktop, right click the Computer icon.
      Choose 'Properties' from the context menu.
      Click the 'Advanced system settings' link.
      Click 'Environment Variables'. In the section 'System Variables', find the PATH environment variable and select it. Click 'Edit'. If the PATH environment variable does not exist, click New.
      In the 'Edit System Variable' (or 'New System Variable') window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
```
 
  Note: You may see a PATH environment variable similar to the following when editing it from the Control Panel:

*%JAVA_HOME%\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem*

  Variables enclosed in percentage signs (%) are existing environment variables. If one of these variables is listed in the Environment Variables window from the Control Panel (such as JAVA_HOME), then you can edit its value. If it does not appear, then it is a special environment variable that the operating system has defined. For example, SystemRoot is the location of the Microsoft Windows system folder. To obtain the value of a environment variable, enter the following at a command prompt. (This example obtains the value of the SystemRoot environment variable):

  echo %SystemRoot%

  Update the PATH Variable (Solaris and Linux)

  You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables (javac, java, javadoc, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

  % /usr/local/jdk1.7.0/bin/javac MyClass.java

  To find out if the path is properly set, execute:

  % java -version

  This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.

  To set the path permanently, set the path in your startup file.

  For C shell (csh), edit the startup file (~/.cshrc):

  set path=(/usr/local/jdk1.7.0/bin )

  For bash, edit the startup file (~/.bashrc):


```
PATH=/usr/local/jdk1.7.0/bin:
  export PATH
  
  For ksh, the startup file is named by the environment variable, ENV. To set the path:
  
  PATH=/usr/local/jdk1.7.0/bin:
  export PATH
  
  For sh, edit the profile file (~/.profile):
  
  PATH=/usr/local/jdk1.7.0/bin:
  export PATH
```
 
  Then load the startup file and verify that the path is set by repeating the java command:

  For C shell (csh):

  % source ~/.cshrc
  % java -version

  For ksh, bash, or sh:

  % . /.profile
  % java -version

  Checking the CLASSPATH variable (All platforms)

  The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)

  The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.

  The default value of the class path is ".", meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.

  To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:

  C:> echo %CLASSPATH%

  On Solaris or Linux, execute the following:

  % echo $CLASSPATH

  If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).

  To modify the CLASSPATH, use the same procedure you used for the PATH variable.

  Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.

  The key to programming in Java or any other programming language is applying logical reasoning and the knowledge of the class libraries.
  So you should have a thorough knowledge of the core classes & their usage. You apply the logic with the knowledge of the API, half
 the work is done!!

  Before I start my lessons on programming. Let me discuss about which IDE to use.
  There are lots of IDEs available like JDeveloper, JBuilder, NetBeans, Eclipse, IntelliJ IDEA etc., 

  My personal favorite is NetBeans ( www.netbeans.org) & IDEA  (*www.jetbrains.com/idea/). If you want to use some light-weight IDE there is JCreator (JCreator &mdash; Java IDE)
  or use a text editor like TextPad (TextPad - the text editor for Windows) If you want to use NetBeans here is a good tutorial (*netbeans.org/kb/docs/java/quickstart.html)

  Please read Coding Conventions: www.oracle.com/technetwork/java/codeconventions-150003.pdf?

  It's important how you name your File name, alignment of the code  how you name your variables etc., 
www.javaprogrammingworld.com/java-coding-conventions.doc?

  As far as OOPS strategy is concerned you must use the methods to access a variable. For example getSalary() method gives you the salary.
  getName() method gives you the name. The methods should be like get / set - getName(), getAddress, setName(), setAddress() etc.,

  For some programs Images are needed. You can download Wallpapers or Images from santabanta.com, mxdpi.com, nabou.com, hdwallpapers.in etc.,
  Some Icons are needed. You can download JIDE's Swing suite demo (JIDE's Swing Component Suite (*www.jidesoft.com/products/download.htm)), Extract the JAR file using WinZip, WinRAR etc.,
  Search for the Image icons in gif & png format. (Search *.gif, *.png). Copy the Icons to some directory & use them in your programs.
  Also some programs need videos in QuickTime format, Audio files in WAV & MP3 format.
  You can use the Digit DVD containing Movie trailers, MP3 music etc., for that purpose.

  An example:


```
// Person.java

public class Person {
//------------
// Attributes.
//------------
    private String name;
    private String ssn;
//----------------
// Constructor(s).
//----------------
    public Person(String name, String ssn) {
        setName(name);
        setSsn(ssn);
    }
// We're replacing the default constructor that got "wiped out"
// as a result of having created a constructor above.
    public Person() {
        setName("?");
        setSsn("???-??-????");
    }
//-----------------
// Get/set methods.
//-----------------
    public void setName(String n) {
        name = n;
    }

    public String getName() {
        return name;
    }

    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    public String getSsn() {
        return ssn;
    }
//-----------------------------
// Miscellaneous other methods.
//---------------------------

// We'll let each subclass determine how it wishes to be
// represented as a String value.
public abstract String toString();
// Used for testing purposes.
public void display() {
System.out.println("Person Information:");
        System.out.println("\tName: " + getName());
        System.out.println("\tSoc. Security No.: " + getSsn());
    }
}
```
 

  First program that I'm going to discuss is a Mouse Drag program. Press the mouse pointer at a specified location and drag it diagonally. The program draws the rectangle
  region in a transulent color.

* MouseDragDemo1.java*  


```
/**
 *
 * @author JGuru
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseDragDemo1 extends JPanel {

    private int mouseX, mouseY, width, height;
    // mouseX - starting point X coordinate
    // mouseY - starting point Y coordinate
    // width - width of the Rectangle
    // height - height of the Rectangle
    private int x, y;
    private Dimension scrDim;
    private int red = 0, green = 124, blue = 0, alpha = 80;
    private Color green2 = new Color(red, green, blue, alpha);
    
    public MouseDragDemo1() {
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        
        // Set the background
        setBackground(Color.orange);
        // Add a Mouse listener
        addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent me) {
                // Starting point of X & Y coordinate
                mouseX = me.getX();
                mouseY = me.getY();
            }
        });
        // Add a Mouse motion listener
        addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseDragged(MouseEvent me) {
                // Calculate the Rectangle coordinates (x, y, width, height)
                x = Math.min(mouseX, me.getX());
                y = Math.min(mouseY, me.getY());
                width = Math.abs(mouseX - me.getX());
                height = Math.abs(mouseY - me.getY());
                repaint();
            }
        });
        setPreferredSize(scrDim);
    }

    /**
     * Overridden to return true which means that children may not overlap.
     * <p>
     * This is a little bit obscure.
     */
    @Override
    public boolean isOptimizedDrawingEnabled() {
        return true;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        // Set Rendering hints properties render for Speed
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        // Set the thickness of the Rectangle
        g2.setStroke(new BasicStroke(3f));
        
        // Translucent green color
        g2.setColor(green2);
        // Draw the Rectangle
        // Fill the Rectangle region with translucent color
        g2.fillRect(x, y, width, height);
        g2.setColor(Color.black);
        // Draw a rectangle outline
        g2.drawRect(x, y, width, height);
        //System.out.println("" + x + " , " + y + " , " + width + " , " + height);
        // Disposes of this graphics context and releases any system resources
        g2.dispose();
    }

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

            public void run() {
                JFrame frame = new JFrame("MouseDrag Demo1");
                frame.add(new MouseDragDemo1());
                //Set the Frame's properties
                frame.pack();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

Here is another Mouse drag program displaying a Image


```
// MouseDragDemo2.java
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MouseDragDemo2 extends JPanel {

    private int mouseX, mouseY, width, height;
    // mouseX - starting point X coordinate
    // mouseY - starting point Y coordinate
    // width - width of the Rectangle
    // height - height of the Rectangle
    private int x, y;
    // Color attributes
    private int red = 0, green = 0, blue = 0, alpha = 80;
    private Color black = new Color(red, green, blue, alpha);
    private BufferedImage image;

    // NOTE : You need a file called Bipasha Basu.jpg under the Images directory in the current directory
    public MouseDragDemo2() {

        //Get the Image
        image = getImage("Images/Bipasha Basu.jpg");
        // Set the background
        setBackground(Color.orange);
        // Add a Mouse listener
        addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent me) {
                // Starting point of X & Y coordinate
                mouseX = me.getX();
                mouseY = me.getY();
            }
        });
        // Add a Mouse motion listener
        addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseDragged(MouseEvent me) {
                // Calculate the Rectangle coordinates (x, y, width, height)
                x = Math.min(mouseX, me.getX());
                y = Math.min(mouseY, me.getY());
                width = Math.abs(mouseX - me.getX());
                height = Math.abs(mouseY - me.getY());
                repaint();
            }
        });
        setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    }

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

    /**
     * Overridden to return true which means that children may not overlap.
     * <p>
     * This is a little bit obscure.
     */
    @Override
    public boolean isOptimizedDrawingEnabled() {
        return true;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        // Set Rendering hints properties render for Speed
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        // Set the thickness of the draw shapes
        g2.setStroke(new BasicStroke(3f));

        if(image != null) {
            g2.drawImage(image, 0, 0, this);
        }
        // Translucent black color
        g2.setColor(black);
        // Draw the Rectangle
        // Fill the Rectangle region with translucent color
        g2.fillRect(x, y, width, height);
        // Green color outline
        g2.setColor(Color.green);
        // Draw a rectangle outline
        g2.drawRect(x, y, width, height);
        // Disposes of this graphics context and releases any system resources
        g2.dispose();
    }

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

            public void run() {
                JFrame frame = new JFrame("MouseDrag Demo2");
                frame.add(new MouseDragDemo2());
                //Set the Frame's properties
                frame.pack();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

*s4.postimg.org/4z21um8k9/Mouse_Drag_Demo2.jpg

   You run the program with your favorite editor or IDE. The program defines two points x1, y1 & x2, y2.

   The place where the mouse is dragged is x1, y1. The place where the Mouse is released is x2,y2.
   We find the width & height of the region & draw a rectangle. You must drag the Mouse diagonally (top to
   bottom or bottom to top) to see the rectangle.

* DesktopPaneDemo.java*


```
/**
 *
 * @author JGuru
 */
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

// NOTE :  A directory by the name "Images" must exist in the current directory & it it must contain atleast 4 or 5 Images in it.
public class DesktopPaneDemo extends JFrame implements ActionListener {

    private JDesktopPane desktop = new JDesktopPane();
    // The gap between internal frames when cascading effect is applied
    private int FRAME_OFFSET = 20;
    private Image image;
    private ImageIcon icon;
    private String path = "Images/";
    private String[] name;
    private int MAX;
    private boolean resizable = true;
    private boolean closable = true;
    private boolean maximizable = true;
    private boolean iconifiable = true;
    private JInternalFrame[] jif;
    private String fileName = "";
    private String title;
    private int X = 25, Y = 30;
    private JMenu file = new JMenu("File");
    private JMenuItem vTile = new JMenuItem("Tile Vertically");
    private JMenuItem hTile = new JMenuItem("Tile Horizontally");
    private JMenuItem cascade = new JMenuItem("Cascade");
    private JMenuItem close = new JMenuItem("Close");
    private int sleepTime = 450;
    private JMenuBar mBar = new JMenuBar();
    private File directory = new File(path);
    private String[] format = ImageIO.getReaderFormatNames();
    private String iState = "";

    private void sleep() {
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException ie) {
        }
    }

    public void updateUI() {
        desktop.updateUI();
        file.updateUI();
        vTile.updateUI();
        hTile.updateUI();
        cascade.updateUI();
        close.updateUI();
        mBar.updateUI();
    }

    public DesktopPaneDemo() {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            System.err.println("Error loading look'n feel!!");
        }
        updateUI();
        // Filter only the Images
        name = directory.list(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                for (int i = 0; i < format.length; i++) {
                    if (name.endsWith(format[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        MAX = name.length;
        if (MAX == 0) {
            System.err.println("Oops, No Images found!!");
            System.exit(1);
        }
        // Restrict to a maximum of 5 Images
        if (MAX > 5) {
            MAX = 5;
        }
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        file.add(cascade);
        file.add(vTile);
        file.add(hTile);
        file.add(close);
        cascade.addActionListener(this);
        vTile.addActionListener(this);
        hTile.addActionListener(this);
        close.addActionListener(this);
        // Set Accelerators
        vTile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_DOWN_MASK));
        hTile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_DOWN_MASK));
        cascade.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK));
        close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_DOWN_MASK));

        mBar.add(file);
        setJMenuBar(mBar);
        // Allocate that many internal frames
        jif = new JInternalFrame[MAX];
        // Show 5 JInternalFrames
        for (int i = 0; i < MAX; i++) {
            fileName = path + name[i];
            image = getImage(fileName);
            // Show only the fileName, sans the file extension
            title = name[i].substring(0, name[i].lastIndexOf("."));
            icon = new ImageIcon(image);
            jif[i] = new JInternalFrame(title, resizable, closable, maximizable, iconifiable);
            jif[i].setFrameIcon(createIcon(image));
            jif[i].add(new JScrollPane(new JLabel(icon)));
            jif[i].setSize(650, 600);
            //Cascade effect
            jif[i].setLocation(X, 10);
            // Icrement X
            X += 85;
            jif[i].setVisible(true);
            desktop.add(jif[i]);
        }
        // When the Component is resized , do the appropriate action
        addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent ce) {
                new Thread(new Runnable() {

                    public void run() {
                        if (iState.equals("Tile Vertical")) {
                            tileVertical();
                        } else if (iState.equals("Tile Horizontal")) {
                            tileHorizontal();
                        } else if (iState.equals("Cascade")) {
                            cascadeFrames();
                        }
                    }
                }).start();
            }
        });
        setContentPane(desktop);
        desktop.setVisible(true);
        setTitle("DesktopPane Demo");
        setSize(scrDim.width / 2 + 250, scrDim.height - 20);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

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

    /* Create an icon for the internal frame */
    public ImageIcon createIcon(Image image) {
        if (image != null) {
            int imgWidth = image.getWidth(null);
            int imgHeight = image.getHeight(null);
            double aspect = ((double) imgWidth) / ((double) imgHeight);
            int maxWidth, maxHeight;
            // If aspect ratio exceeds 1.3333
            if (aspect > 1.3333) {
                // Fix the width as maxWidth, calculate the maxHeight
                maxWidth = 28;
                maxHeight = (int) (((double) maxWidth) / aspect);
            } else {
                // Fix the height as iconHeight, calculate the maxWidth for this
                maxHeight = 28;
                maxWidth = (int) (((double) maxHeight) * aspect);
            }
            return new ImageIcon(image.getScaledInstance(maxWidth, maxHeight, Image.SCALE_SMOOTH));
        }
        return null;
    }

    public void actionPerformed(ActionEvent ae) {
        final Object source = ae.getSource();
        new Thread(new Runnable() {

            public void run() {
                if (source == vTile) {
                    iState = "Tile Vertical";
                    tileVertical();

                } else if (source == hTile) {
                    iState = "Tile Horizontal";
                    tileHorizontal();

                } else if (source == cascade) {
                    iState = "Cascade";
                    cascadeFrames();

                } else {
                    System.exit(0);
                }
            }
        }).start();
    }
    /* Cascade the internal frames */

    public void cascadeFrames() {
        int x = 0;
        int y = 0;
        JInternalFrame allFrames[] = desktop.getAllFrames();
        int frameHeight = (desktop.getBounds().height - 5) - allFrames.length * FRAME_OFFSET;
        int frameWidth = (desktop.getBounds().width - 5) - allFrames.length * FRAME_OFFSET;
        for (int i = allFrames.length - 1; i >= 0; i--) {
            allFrames[i].setSize(frameWidth, frameHeight);
            allFrames[i].setLocation(x, y);
            x = x + FRAME_OFFSET;
            y = y + FRAME_OFFSET;
            sleep();
        }
    }

    /**
     * Tile all internal frames horizontally
     */
    public void tileHorizontal() {
        JInternalFrame allFrames[] = desktop.getAllFrames();
        int frameHeight = desktop.getBounds().height / allFrames.length;
        int frameWidth = desktop.getBounds().width / allFrames.length;
        int wholeHeight = desktop.getBounds().height;
        int x = 0, y = 0;
        for (int i = 0; i < allFrames.length; i++) {
            allFrames[i].setSize(frameWidth, wholeHeight);
            allFrames[i].setLocation(x, 0);
            x = x + frameWidth;
            y = y + frameHeight;
            sleep();
        }
    }

    /**
     * Tile all internal frames vertically
     */
    public void tileVertical() {
        JInternalFrame[] frames = desktop.getAllFrames();
        if (frames.length == 0) {
            return;
        }
        int cols = (int) Math.sqrt(frames.length);
        int rows = (int) (Math.ceil(((double) frames.length) / cols));
        int lastRow = frames.length - cols * (rows - 1);
        Rectangle dBounds = desktop.getBounds();
        int height = 0, width = 0;
        if (lastRow == 0) {
            rows--;
            height = dBounds.height / rows;
        } else {
            height = dBounds.height / rows;
            if (lastRow < cols) {
                rows--;
                width = dBounds.width / lastRow;
                for (int i = 0; i < lastRow; i++) {
                    frames[cols * rows + i].setBounds(i * width, rows * height,
                            width, height);
                }
            }
        }
        width = dBounds.width / cols;
        for (int j = 0; j < rows; j++) {
            for (int i = 0; i < cols; i++) {
                frames[i + j * cols].setBounds(i * width, j * height,
                        width, height);
            }
            sleep();
        }
    }

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

            public void run() {
                new DesktopPaneDemo();
            }
        });
    }
}
```

*s2.postimg.org/gbbz96ddh/Desktop_Pane_Demo.jpg

 This example demonstrates the internal frame. We show various effects like tiling vertically, tiling horizintally, cascading etc.,


 This program displays an Image when the Mouse hovers over the blue square region. When you move the Mouse from the square , the
 Image disappears from the screen!! 

 *MouseEnteredDemo.java*

```
/**
 *
 * @author JGuru
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;

// NOTE : You need a directory by the name "Images" in the current directory & a file by the name "Aishwarya.jpg" in it.
 If you have some other image , then change the "Aishwarya.jpg" to corresponding Image name in your directory.

public class MouseEnteredDemo extends JPanel {

    // squareX - starting X coordinate of the square
    // squareY - starting Y coordinate of the square
    // squareWidth - width of the square
    // squareHeight - height of the square
    private int squareX = 250, squareY = 300, squareWidth = 50, squareHeight = 50;
    private int imgWidth, imgHeight;
    private int X, Y;
    private Image image;
    // Coordinates at which the Image should be displayed
    private int imgX, imgY;
    private static Dimension scrDim;
    private int appWidth, appHeight;
    private boolean withInArea = false;
    private String message = "Hai, I'm Aishwarya!!";

    public MouseEnteredDemo() {
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        try {
            image = ImageIO.read(new File("Images/Aishwarya.jpg"));
        } catch (IOException ioe) {
            System.err.println("Error loading Image!!");
            System.exit(1);
        }

        if (image != null) {
            imgWidth = image.getWidth(null);
            imgHeight = image.getHeight(null);

            // Scale down the Image if it's larger than half Screen size
            if (imgWidth > scrDim.width / 2 || imgHeight > scrDim.height / 2) {
                imgWidth = imgWidth / 2;
                imgHeight = imgHeight / 2;
                image = image.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH);
            }
        }

        addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseMoved(MouseEvent me) {
                X = me.getX();
                Y = me.getY();
                //Region within the square!
                // Mouse X, Y coordinates correction
                if ((X >= squareX && X <= (squareX + squareWidth)) && (Y >= squareY && Y <= (squareY + squareHeight))) {
                    withInArea = true;
                    repaint();
                } else {
                    withInArea = false;
                    repaint();
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        appWidth = getWidth();
        appHeight = getHeight();

        Graphics2D g2d = (Graphics2D) g;
        // Set the background 
        g2d.setColor(Color.green.darker().darker());
        g2d.fillRect(0, 0, appWidth, appHeight);
        g2d.setStroke(new BasicStroke(3f));
        // Draw the square
        drawSquare(g2d, false);
        // Set the rendering hints
        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);
        g2d.setStroke(new BasicStroke(3f));
        g2d.setFont(new Font("Serif", Font.BOLD, 23));
        // If within the region
        if (withInArea) {
            // center the Image
            imgX = (getWidth() - imgWidth) / 2;
            imgY = (getHeight() - imgHeight) / 2;
            // Draw the highlight square
            drawSquare(g2d, true);
            // Draw the Image
            if (image != null) {
                g2d.drawImage(image, imgX, imgY, this);
            }
            // Draw a Rectangular border
            g2d.setColor(Color.red);
            g2d.drawRect(imgX, imgY, imgWidth, imgHeight);
            g2d.setColor(Color.red);
            g2d.drawString("Inside Square Region", 25, scrDim.height - 150);
            g2d.setColor(Color.magenta);
            g2d.drawString(message, imgX + 50, imgY - 50);
        } else {
            g2d.drawString("Outside Square Region", 25, scrDim.height - 150);
        }
        g2d.setColor(Color.black);
        // Draw the cursor coordinates 
        g2d.drawString("X = " + X + " , Y = " + Y, 25, scrDim.height - 100);
        // Disposes of this graphics context and releases any system resources that it is using
        g2d.dispose();
    }

    public void drawSquare(Graphics2D g, boolean highlight) {
        if (highlight) {
            //Draw a Red color square
            g.setColor(Color.red);
            g.fillRect(squareX, squareY, squareWidth, squareHeight);
            //Draw a yellow rectangular outline
            g.setColor(Color.yellow);
            g.drawRect(squareX, squareY, squareWidth, squareHeight);
        } else {
            //Draw a Blue color square
            g.setColor(Color.blue);
            g.fillRect(squareX, squareY, squareWidth, squareHeight);
            //Draw a yellow rectangular outline
            g.setColor(Color.yellow);
            g.drawRect(squareX, squareY, squareWidth, squareHeight);
        }
    }

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

            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MouseEnteredDemo());
                frame.setTitle("MouseEntered Demo");
                frame.setSize(scrDim);
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

*s4.postimg.org/lx5nu77bt/Mouse_Entered_Demo.jpg

 Let's write a  directory lister program to list the contents of a directory.

 *DirLister3.java* 

```
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FilenameFilter;
import javax.swing.*;
import java.text.NumberFormat;

// can apply a Filter for wildcards

/*
 * Swing's Threading Policy
 *==========================

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.
Typical Swing applications do processing in response to an event generated from a user gesture. For example, clicking on a JButton notifies all ActionListeners
 added to the JButton. As all events generated from a user gesture are dispatched on the event dispatching thread, most developers are not impacted by the restriction.

Where the impact lies, however, is in constructing and showing a Swing application. Calls to an application's main method, or methods in Applet, are not
 invoked on the event dispatching thread. As such, care must be taken to transfer control to the event dispatching thread when constructing and showing
 an application or applet. The preferred way to transfer control and begin working with Swing is to use invokeLater. The invokeLater method schedules a
 Runnable to be processed on the event dispatching thread. The following two examples work equally well for transferring control and starting up a Swing
 application:
 *
 */

public class DirLister3 extends JFrame implements ActionListener, ItemListener, Runnable {

    JTextArea area;
    JTextField input = new JTextField(25);
    File file;
    String[] pattern = {"*.*", "*.java", "*.txt", "*.mp3", "*.wav", "*.mp4", "*.jpg", "*.jpeg",
        "*.bmp", "*.tiff", "*.png", "*.cpp", "*.py", "*.c", "*.html", "*.xml", "*.mpeg", "*.mov", "*.asf", "*.wav"};
    JComboBox wildCard = new JComboBox(pattern);
    int dotIndex = -1;
    String patternMatch = "";
    String separator = System.getProperty("file.separator");
    Font font = new Font("Monospaced", Font.BOLD, 13);
    JProgressBar progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    JButton search = new JButton("Search");
    JLabel statusBar = new JLabel("Ready");
    int fileCount = 0;
    int dirCount = 0;
    NumberFormat nFormat = NumberFormat.getInstance();
    String path = "";
    int sIndex = -1;
    Thread runner = null;

    public DirLister3() {
        input.setFont(font);
        input.addActionListener(this);
        search.addActionListener(this);
        progressBar.setIndeterminate(true);
        area = new JTextArea();
        area.setEditable(false);
        area.setFont(font);
        area.setForeground(Color.green);
        area.setBackground(Color.black);
        wildCard.addItemListener(this);
        bottomPanel.add(new JLabel("Processing, Please wait .."));
        bottomPanel.add(progressBar);
        JScrollPane scroller = new JScrollPane(area);
        JPanel top = new JPanel(new FlowLayout(FlowLayout.LEFT));
        top.add(new JLabel("Enter Directory :"));
        top.add(input);
        top.add(search);
        top.add(new JLabel("Wild Card :"));
        top.add(wildCard);
        // Add these Components to the NORTH
        add(top, BorderLayout.NORTH);
        add(scroller, BorderLayout.CENTER);
        setSize(850, 750);
        setTitle("Directory Lister3");
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == input || source == search) {
            search.setEnabled(false);
            area.setText("");
            //Get the path or the dir to be listed
            path = input.getText();
            //Make sure the path exists and is a directory
            file = new File(path);
            if (!file.isDirectory()) {
                if (path.equals("")) {
                    // Do nothing
                } else {
                    JOptionPane.showMessageDialog(null, "The specified directory \"" + path + "\" does not exist!!",
                     "Warning", JOptionPane.WARNING_MESSAGE);
                    // Clear the input text
                    input.setText("");
                }
            } else {
                start();
            }
        }
    }

    public void start() {
        if (runner == null) {
            runner = new Thread(this);
            runner.setPriority(Thread.MIN_PRIORITY);
            runner.start();
        }
    }

    public void run() {
        search();
    }

    public void search() {
        // Clear the TextArea contents
        area.setText("");
        fileCount = 0;
        dirCount = 0;
        search.setEnabled(false);
        //Remove statusBar
        remove(statusBar);
        validate();
        // Add bottomPanel to show Progress
        add(bottomPanel, BorderLayout.SOUTH);
        bottomPanel.validate();
        validate();
        input.setEnabled(false);
        wildCard.setEnabled(false);
        area.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        recurse(file, 0);
        area.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        input.setEnabled(true);
        wildCard.setEnabled(true);
        search.setEnabled(true);
        remove(bottomPanel);
        if (patternMatch.equals("")) {
            statusBar.setText(" Directories = " + nFormat.format(dirCount) + " , Files = " + nFormat.format(fileCount));
        } else {
            // When a filter is applied, show only files count, exclude directories count
            statusBar.setText(" Files = " + nFormat.format(fileCount));
        }
        add(statusBar, BorderLayout.SOUTH);
        statusBar.validate();
        statusBar.repaint(150);
        validate();
        // Move the Caret position of the TextArea to the bottom
        int length = area.getDocument().getLength();
        area.setCaretPosition(length);
        // Assign 'null' to Thread runner
        // Only if the runner is 'null', a new Thread is started!!
        runner = null;
    }

    public void itemStateChanged(ItemEvent ie) {
        patternMatch = (String) wildCard.getSelectedItem();
        if (patternMatch.equals("*.*")) {   // No filter
            patternMatch = "";
        } else {   //Apply filter
            dotIndex = patternMatch.lastIndexOf(".");
            // Get only the file extension
            patternMatch = patternMatch.substring(dotIndex + 1);
        }
        start();
    }

    // Recursively list the contents of the directory
    public void recurse(File dir, int depth) {    // Catch any Exceptions if it's thrown
        try {
            String contents[] = dir.list(new FilenameFilter() {

                File file = null;

                public boolean accept(File dir, String name) {
                    file = new File(dir + separator + name);
                    // Get pattern match & directory entries
                    // We need directory entries to list them recursively
                    if (name.endsWith(patternMatch) || file.isDirectory()) {
                        return true;
                    }
                    return false;
                }
            });
            // For each child ...
            for (int i = 0; i < contents.length; i++) {
                File child = new File(dir, contents[i]);
                // If wild cards are not used, then indent
                if (patternMatch.equals("")) {
                    //Indent ...
                    for (int spaces = 0; spaces < depth; spaces++) {
                        area.append("  ");
                    }
                }

                if (child.isDirectory()) {
                    dirCount++;
                    // Don't show directory entries for wild cards (For eg., *.java, *.bmp, *.jpg etc.,)
                    if (patternMatch.equals("")) {
                        area.append("< DIR > " + contents[i] + "\n");
                    }
                    // Process recursively
                    recurse(child, depth + 1);
                } else {
                    if (patternMatch.equals("")) {
                        area.append(" " + contents[i] + "\n");
                    } else {
                        // Show path info also, for filter (*.jpg, *.java etc.,)
                        path = child.getPath();
                        sIndex = path.lastIndexOf(separator);
                        // Get only the path excluding file name
                        path = path.substring(0, sIndex);
                        area.append(" " + contents[i] + "  [" + path + "]" + "\n");
                    }
                    fileCount++;
                }
            }
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        //Recursively list the contents of a directory
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new DirLister3();
            }
        });
    }
}
```
 This lists the contents of the specified directory recursively.
 Enter some directory name (for eg., D:/ ) , press the 'search' button to list it contents.


*How do I play sound file in a Java application? * 

 Here is a program that plays WAV audio file. It uses the "javax.sound" package to play the audio file.


* CoreJavaSound.java*

```
import java.awt.FlowLayout;
import javax.sound.sampled.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;

public class CoreJavaSound extends JFrame implements LineListener , ActionListener
{

    File soundFile;
    JDialog playingDialog;
    Clip clip;
    JButton play = new JButton("Play");
    JButton pause = new JButton("Pause");
    JButton quit = new JButton("Quit");

    public static void main (String[] args)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        if(file != null)
        {
            try
            {
                CoreJavaSound s = new CoreJavaSound (file);
            } catch (Exception e) {
            e.printStackTrace();
            }
        }
    }

    public CoreJavaSound (File file)  throws LineUnavailableException, IOException, UnsupportedAudioFileException
    {
        soundFile = file;
        // prepare a dialog to display while playing
        JOptionPane pane = new JOptionPane ("Playing " + file.getName(),
                                            JOptionPane.PLAIN_MESSAGE);
        playingDialog = pane.createDialog (null, "Application Sound");
        playingDialog.pack();

        // get and play sound
        Line.Info linfo = new Line.Info (Clip.class);
        Line line = AudioSystem.getLine (linfo);
        clip = (Clip) line;
        clip.addLineListener (this);
        AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
        // Open the audio file
        clip.open (ais);
        // Start playing the audio
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        play.addActionListener(this);
        pause.addActionListener(this);
        quit.addActionListener(this);
        panel.add(play);
        panel.add(pause);
        panel.add(quit);
        add(panel);
        // Frame's properties
        setTitle("Java Sound");
        setSize(450, 400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent ae)
    {
        Object source = ae.getSource();
        if(source == play)
        {
            clip.start();
        }
        else if(source == pause)
        {
            clip.stop();
        }
        else if(source == quit)
        {
            System.exit(0);
        }
    }
    
    // LineListener
    public void update (LineEvent le) 
    {
        LineEvent.Type type = le.getType();
        if (type == LineEvent.Type.OPEN) 
        {
            System.out.println ("OPEN");
        } else if (type == LineEvent.Type.CLOSE) 
        {
            System.out.println ("CLOSE");
            
        } else if (type == LineEvent.Type.START) 
        {
            System.out.println ("START");
            playingDialog.setVisible(true);
        } else if (type == LineEvent.Type.STOP) 
        {
            System.out.println ("STOP");
            playingDialog.setVisible(false);
            clip.close();
        }

    }
}
```

*How do I develop a Image processing program in Java ?*

 You must study the classes in the  "java.awt.image" package & their usage.
 It will help in developing some Image processing programs.

 The immediate mode imaging APIs in the Java 2D™ API can be grouped into six categories: interfaces, image data classes, image operation classes, sample model classes, color model classes, and exceptions.
 5.1.1 Imaging Interfaces
 Interface

*Description*: 


 BufferedImageOp - Describes single-input/single-output operations performed on BufferedImage objects. Implemented by AffineTransformOp, ColorConvertOp, ConvolveOp, LookupOp, and RescaleOp.

 RasterOp - Defines single-input/single-output operations performed on Raster objects. Implemented by AffineTransformOp, BandCombineOp, ColorConvertOp, ConvolveOp, LookupOp, and RescaleOp.

 RenderedImage - Defines a common protocol for objects that contain or can produce image data in the form of Rasters.

 WritableRenderedImage - Extends: RenderedImage Defines a common protocol for objects that contain or can produce image data in the form of Rasters which can be modified.

 TileObserver - Defines a protocol for objects that want to be notified when the modification state of a WritableRenderedImage changes.

*5.1.2 Image Data Classes*

*Class                    Description*


 BufferedImage - Extends: Image Implements: WriteableRenderedImage
 An image with an accessible data buffer. A BufferedImage has a ColorModel and a Raster of image data.

 ByteLookupTable - Extends: LookupTable A LookupTable that contains byte data.

 DataBuffer - Wraps one or more data arrays holding pixel data. Each data array is called a bank.

 DataBufferByte - Extends: DataBuffer (Final)

 A data buffer that stores bytes of data. (Used in Java Advanced Imaging API)

 DataBufferInt - Extends: DataBuffer (Final)) A data buffer that stores integer data.(Used in Java Advanced Imaging API)

 DataBufferShort - Extends: DataBuffer (Final) A data buffer that stores short data.(Used in Java Advanced Imaging API)

 DataBufferUShort - Extends: DataBuffer (Final) A data buffer that stores unsigned short data.

 Kernel - A matrix that describes how an input pixel and its surrounding pixels affect the value of an output pixel in a ConvolveOp filtering operation.

 LookupTable - Extends: Object A table that maps values from single-banded pixel data to color values.

 Raster  - A rectangular array of pixels from which you can retrieve image data. A Raster contains a DataBuffer and a SampleModel.

 ShortLookupTable - Extends: LookupTable A lookup table that contains short data.

 WritableRaster - Extends: Raster A Raster that you can modify.

*Image Operation Classes*

 Class                   Description


 AffineTransformOp - Implements: BufferedImageOp, RasterOp A class that defines an affine transform to perform a linear mapping from 2D coordinates in a source Image or Raster to 2D coordinates in the destination image or Raster. This class can perform either bilinear or nearest neighbor affine transform operations.

 BandCombineOp - Implements: RasterOp Using a specified matrix, this operation performs an arbitrary linear combination of bands in a Raster.

 BufferedImageFilter - Extends: ImageFilter An ImageFilter that provides a simple means of using a BufferedImageOp (a single-source/single-destination image operator) to filter a BufferedImage or Raster.

 ColorConvertOp - Implements: BufferedImageOp, RasterOp Performs a pixel-by-pixel color conversion of the data in the source image.

 ConvolveOp - Implements: BufferedImageOp, RasterOp Uses a Kernel to perform a convolution on the source image. A convolution is a spatial operation where the pixels surrounding the input pixel are multiplied by a kernel value to generate the value of the output pixel. The Kernel mathematically defines the relationship between the pixels in the immediate neighborhood of the input pixel and the output pixel.

 LookupOp  - Implements: BufferedImageOp, RasterOp. Performs a lookup operation from the source to the destination. For Rasters, the lookup operates on sample values. For BufferedImages, the lookup operates on color and alpha components.

 RescaleOp - Implements: BufferedImageOp, RasterOp. Performs a pixel-by-pixel rescaling of the data in the source image by multiplying each pixel value by a scale factor and then adding an offset.

*Sample Model Classes*

 Class                 Description

 BandedSampleModel -  Extends: ComponentSampleModel (Final) Provides access to image data stored with like samples stored as bands in separate banks of a DataBuffer. A pixel consists of one sample from each band.

 ComponentSampleModel - Extends: SampleModel .Provides access to image data stored with each sample of a pixel residing in a separate element of a DataBuffer. Different types of pixel interleaving are supported.

 MultiPixelPackedSampleModel - Extends: SampleModel. Provides access to image data stored with multiple one-sample pixels packed into one element of a DataBuffer.

 PixelInterleavedSampleModel - Extends: ComponentSampleModel. Provides access to image data stored with the sample data for each pixel in adjacent elements of the data array, and all elements in a single bank of a DataBuffer.

 SampleModel - An abstract class that defines a mechanism for extracting sample data from an image without knowing how the underlying data is stored in a DataBuffer.

 SinglePixelPackedSampleModel - Extends: SampleModel. Provides access to image data stored with all the samples belonging to an individual pixel packed into one element of a DataBuffer.

*Color Model Classes*

 Class         Description


 ColorModel - Implements: Transparency. JDK1.1 class. An abstract class that defines methods for translating from image pixel values to color components such as red, green, and blue.

 ComponentColorModel - Extends: ColorModel .A ColorModel that can handle an arbitrary ColorSpace and an array of color components to match the ColorSpace. This class can be used to represent most color models on most types of GraphicsDevices.

 DirectColorModel - Extends: PackedColorModel .JDK1.1 class. A ColorModel that represents pixel values that have RGB color components embedded directly in the bits of the pixel. This color model is similar to an X11 TrueColor visual. The default RGB ColorModel returned by ColorModel.getRGBdefault is a DirectColorModel.

 IndexColorModel - Extends: ColorModel. JDK1.1 class. A ColorModel that represents pixel values that are indices into a fixed color map in the sRGB ColorSpace.

 PackedColorModel - Extends: ColorModel .An abstract ColorModel that represents pixel values that have color components embedded directly in the bits of a pixel. DirectColorModel extends PackedColorModel to support pixels that contain RGB color components.


*Exception Classes*

 Class         Description

 ImagingOpException - Extends: RuntimeException .Thrown if one of the BufferedImageOp or RasterOp filter methods can’t process the image.

 RasterFormatException - Extends: RuntimeException .Thrown if there is invalid layout information in the Raster.

*Immediate Mode Imaging Concepts*

 The immediate mode imaging model supports fixed-resolution images stored in memory. The model also supports filtering operations on image data. A number of classes and interfaces are used in this model.

 BufferedImage and supporting classes

 BufferedImage provides general image management. A BufferedImage can be created directly in memory and used to hold and manipulate image data retrieved from a file or URL. 
 A BufferedImage can be displayed using any Graphics2D object for a screen device, or rendered to any other destination using appropriate Graphics2D context. 
 A BufferedImage object contains two other objects: a Raster and a ColorModel.

 The Raster class provides image data management. It represents the rectangular coordinates of the image, maintains image data in memory, and provides a mechanism for creating
 multiple subimages from a single image data buffer. It also provides methods for accessing specific pixels within an image. A Raster object contains two other objects, a DataBuffer and a SampleModel.

 The DataBuffer class holds pixel data in memory.

 The SampleModel class interprets data in the buffer and provides it as individual pixels or rectangular ranges of pixels.

 The ColorModel class provides a color interpretation of pixel data provided by the image’s sample model.

Here is a demo program

*ProcessImage.java* 

```
/**
 *
 * @author JGuru
 */
// ProcessImage - Do some effects like Blur, Sharpen, Contrast, Negative etc.,
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileFilter;

class ProcessImage extends JFrame implements ActionListener {

    JLabel label = new JLabel("", JLabel.CENTER);
    JFileChooser fc = new JFileChooser(".");
    JLabel message = new JLabel("Ready", JLabel.LEFT);
    BufferedImage buffImg;
    // MenuItems ...
    JMenuItem open = new JMenuItem("Open...");
    JMenuItem revert = new JMenuItem("Revert");
    JMenuItem blur = new JMenuItem("Blur");
    JMenuItem edgeDetect = new JMenuItem("Edge Detect");
    JMenuItem emboss = new JMenuItem("Emboss");
    JMenuItem posterize = new JMenuItem("Posterize");
    JMenuItem sharpen = new JMenuItem("Sharpen");
    JMenuItem negative = new JMenuItem("Negative");
    JMenuItem threshold = new JMenuItem("Threshold");
    JMenuItem grayScale = new JMenuItem("GrayScale");
    JMenuItem exit = new JMenuItem("Exit");
    Image image = null;
    int imgWidth = -1;
    int imgHeight = -1;

    // Get supported Image formats (remove duplicate entries)
    public String[] getReaderFormats()
    {
        String []rFormat = ImageIO.getReaderFormatNames();
        Set <String>set = new HashSet<String>();
        String imgformat = "";
        // Remove duplicate entries
        for (int i = 0; i < rFormat.length; i++) {
            imgformat = rFormat[i];
            imgformat = imgformat.toLowerCase();
            set.add(imgformat);
        }
        String []frmt = new String[set.size()];
        return set.toArray(frmt);
    }

    public void updateUI() {
        open.updateUI();
        revert.updateUI();
        blur.updateUI();
        edgeDetect.updateUI();
        emboss.updateUI();
        posterize.updateUI();
        sharpen.updateUI();
        negative.updateUI();
        threshold.updateUI();
        grayScale.updateUI();
        exit.updateUI();
        fc.updateUI();
    }

    // Enable or disable menuitems
    @Override
    public void setEnabled(boolean condition) {
        revert.setEnabled(condition);
        blur.setEnabled(condition);
        edgeDetect.setEnabled(condition);
        emboss.setEnabled(condition);
        posterize.setEnabled(condition);
        sharpen.setEnabled(condition);
        negative.setEnabled(condition);
        threshold.setEnabled(condition);
        grayScale.setEnabled(condition);
    }

    ProcessImage(String title) {
        super(title);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (UnsupportedLookAndFeelException e) {
            System.err.println("Unsupported Look 'n Feel!!!");
            // handle exception
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found!!!");
            // handle exception
        } catch (InstantiationException e) {
            System.err.println("Instantiation exception!!!");
            // handle exception
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access exception!!!");
            // handle exception
        }
        updateUI();
        open.addActionListener(this);
        revert.addActionListener(this);
        blur.addActionListener(this);
        edgeDetect.addActionListener(this);
        emboss.addActionListener(this);
        posterize.addActionListener(this);
        sharpen.addActionListener(this);
        negative.addActionListener(this);
        threshold.addActionListener(this);
        grayScale.addActionListener(this);
        exit.addActionListener(this);
        JMenuBar mBar = new JMenuBar();

        JMenu menu = new JMenu("File");
        menu.addActionListener(this);

        //Disable menuitems other than 'Open' & 'Exit"!
        // Since there is no Image to process!!
        revert.setEnabled(false);
        blur.setEnabled(false);
        edgeDetect.setEnabled(false);
        emboss.setEnabled(false);
        posterize.setEnabled(false);
        sharpen.setEnabled(false);
        negative.setEnabled(false);
        threshold.setEnabled(false);
        grayScale.setEnabled(false);
        menu.add(open);
        menu.addSeparator();
        menu.add(revert);
        menu.addSeparator();
        menu.add(exit);

        mBar.add(menu);

        menu = new JMenu("Effects");
        menu.addActionListener(this);

        menu.add(blur);
        menu.add(edgeDetect);
        menu.add(emboss);
        menu.add(negative);
        menu.add(posterize);
        menu.add(sharpen);
        menu.add(threshold);
        menu.add(grayScale);
        mBar.add(menu);
        setJMenuBar(mBar);

        JScrollPane scroller = new JScrollPane(label);
        add(scroller, BorderLayout.CENTER);
        add(message, BorderLayout.SOUTH);
        setSize(550, 600);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    // Blur the Image
    public BufferedImage blur() {
        float ninth = 1.0f / 9.0f;

        float[] blurKernel = {
            ninth, ninth, ninth,
            ninth, ninth, ninth,
            ninth, ninth, ninth
        };

        BufferedImageOp blurOp = new ConvolveOp(new Kernel(3, 3, blurKernel));
        return blurOp.filter(buffImg, null);
    }
    // Sharpen the Image
    public BufferedImage sharpen() {
        float[] sharpenKernel = {
            0.0f, -1.0f, 0.0f,
            -1.0f, 5.0f, -1.0f,
            0.0f, -1.0f, -0.0f
        };

        BufferedImageOp sharpenOp = new ConvolveOp(new Kernel(3, 3, sharpenKernel));
        return sharpenOp.filter(buffImg, null);
    }
    //Edge detect the Image
    public BufferedImage edgeDetect() {
        float[] edgeKernel = {
            0.0f, -1.0f, 0.0f,
            -1.0f, 4.0f, -1.0f,
            0.0f, -1.0f, 0.0f
        };

        BufferedImageOp edgeOp = new ConvolveOp(new Kernel(3, 3, edgeKernel));
        return edgeOp.filter(buffImg, null);
    }
    //Convert the Image to grayScale
    public BufferedImage grayScale() {
        //Converting a Color Image to Gray
        //Darker Gray
        ColorSpace cs = ColorSpace.getInstance(
                ColorSpace.CS_GRAY);
        ColorConvertOp op = new ColorConvertOp(cs, null);
        return op.filter(buffImg, null);
    }
    // Emboss the Image
    public BufferedImage emboss(BufferedImage buff) {
        int width = buff.getWidth();
        int height = buff.getHeight();

        BufferedImage dst;
        dst = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // Start changing pixel-by-pixel
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int upperLeft = 0;
                int lowerRight = 0;

                if (i > 0 && j > 0) {
                    upperLeft = buff.getRGB(j - 1, i - 1);
                }

                if (i < height - 1 && j < width - 1) {
                    lowerRight = buff.getRGB(j + 1, i + 1);
                }

                int redDiff = ((lowerRight >> 16) & 255)
                        - ((upperLeft >> 16) & 255);

                int greenDiff = ((lowerRight >> 8) & 255)
                        - ((upperLeft >> 8) & 255);

                int blueDiff = (lowerRight & 255)
                        - (upperLeft & 255);

                int diff = redDiff;
                if (Math.abs(greenDiff) > Math.abs(diff)) {
                    diff = greenDiff;
                }
                if (Math.abs(blueDiff) > Math.abs(diff)) {
                    diff = blueDiff;
                }

                int grayColor = 128 + diff;

                if (grayColor > 255) {
                    grayColor = 255;
                } else if (grayColor < 0) {
                    grayColor = 0;
                }

                int newColor = (grayColor << 16) + (grayColor << 8)
                        + grayColor;

                dst.setRGB(j, i, newColor);
            }
        }
        return dst;
    }
    // Posterize the Image
    public BufferedImage posterize() {
        short[] posterize = new short[256];

        for (int i = 0; i < posterize.length; i++) {
            posterize[i] = (short) (i - i % 32);
        }

        BufferedImageOp posterizeOp =
                new LookupOp(new ShortLookupTable(0, posterize), null);

        return posterizeOp.filter(buffImg, null);
    }
    // Image negative
    public BufferedImage negative() {
        short[] invert = new short[256];

        for (int i = 0; i < invert.length; i++) {
            invert[i] = (short) (255 - i);
        }

        BufferedImageOp invertOp =
                new LookupOp(new ShortLookupTable(0, invert), null);

        return invertOp.filter(buffImg, null);
    }
    // Threshold Image
    public BufferedImage threshold() {
        short[] threshold = new short[256];

        for (int i = 0; i < threshold.length; i++) {
            threshold[i] = (i < 128) ? (short) 0 : (short) 255;
        }

        BufferedImageOp thresholdOp = new LookupOp(new ShortLookupTable(0, threshold), null);

        return thresholdOp.filter(buffImg, null);
    }
    // Convert the Image to BufferedImage
    public BufferedImage toBufferedImage(Image image) {
        if (image != null) {
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage buff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g2 = buff.getGraphics();
            g2.drawImage(image, 0, 0, null);
            g2.dispose();
            return buff;
        }
        return null;
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == exit) {
            System.exit(0);
        } else if (source == revert) {
            label.setIcon(new ImageIcon(buffImg));
            message.setText("Image Reverted");
        } else if (source == open) {
            fc.setAccessory(new ImagePreview(fc));
            fc.setPreferredSize(new Dimension(780, 423));
            fc.setAcceptAllFileFilterUsed(false);
            fc.setCurrentDirectory(new File("Samples"));
            final String[] format = getReaderFormats();
            fc.addChoosableFileFilter(new FileFilter() {

                @Override
                public boolean accept(File file) {
                    String fileName = file.getName();
                    for (int i = 0; i < format.length; i++) {
                        // Show directory & images files only
                        if (fileName.endsWith(format[i]) || file.isDirectory()) {
                            return true;
                        }
                    }
                    return false;
                }

                // Show something like "*.jpg,*.jpeg,*.bmp,*.tiff,*.gif,*.jpeg2000" etc.,
                @Override
                public String getDescription() {   
                    String str = "";
                    for (int i = 0; i < format.length; i++) {
                        str += "*." + format[i] + ",";
                    }
                    return str;
                }
            });
            int result = fc.showOpenDialog(this);

            if (result != 0) {
                return;
            }

            File file = fc.getSelectedFile();
            String fileName = file.toString();
            if (file == null) {
                return;
            } else {
                //Fetch the Image for processing
                try {   
                    image = ImageIO.read(new File(fileName));
                    imgWidth = image.getWidth(null);
                    imgHeight = image.getHeight(null);
                } catch (Exception ioe) {
                    System.err.println("Error loading the Image!!");
                    JOptionPane.showMessageDialog(null, "Not a valid Image!!!", "Error", JOptionPane.ERROR_MESSAGE);
                    //Disable menuitems other than 'Open' & 'Exit"!
                    // Since there is no Image to process!!
                    setEnabled(false);
                }
                //Enable the MenuItems now!
                setEnabled(true);
                // Convert Image to BufferedIage
                buffImg = toBufferedImage(image);
                // Update the label
                label.setIcon(new ImageIcon(buffImg));
                message.setText("Ready");
                pack();
            }
        } else if (source == blur) {
            label.setIcon(new ImageIcon(blur()));
            message.setText("Image Blurred");
            
        } else if (source == edgeDetect) {
            label.setIcon(new ImageIcon(edgeDetect()));
            message.setText("Image EdgeDetected");
            
        } else if (source == sharpen) {
            label.setIcon(new ImageIcon(sharpen()));
            message.setText("Image Sharpened");
            
        } else if (source == negative) {
            label.setIcon(new ImageIcon(negative()));
            message.setText("Image Negative");
            
        } else if (source == threshold) {
            label.setIcon(new ImageIcon(threshold()));
            message.setText("Image Threshold");
            
        } else if (source == emboss) {
            label.setIcon(new ImageIcon(emboss(buffImg)));
            message.setText("Image Embossed");
            
        } else if (source == posterize) {
            label.setIcon(new ImageIcon(posterize()));
            message.setText("Image Posterized");
            
        } else {   // GrayScale
            label.setIcon(new ImageIcon(grayScale()));
            message.setText("Image GrayScaled");
        }
    }

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

            public void run() {
                new ProcessImage("Process Image");
            }
        });
    }
    
    class ImagePreview extends JComponent implements PropertyChangeListener {
    
        ImageIcon thumbnail = null;
        int width = 180;
    
        public ImagePreview(JFileChooser fc) {
            setPreferredSize(new Dimension(width, 50));
            fc.addPropertyChangeListener(this);
            setBorder(new BevelBorder(BevelBorder.LOWERED));
        }
    
        public void loadImage(File f) {
            if (f == null) {
                thumbnail = null;
            } else {
                ImageIcon tmpIcon = new ImageIcon(getImage(f.getPath()));
                if (tmpIcon.getIconWidth() > width) {
                    thumbnail = new ImageIcon(
                            tmpIcon.getImage().getScaledInstance(width, -1, Image.SCALE_SMOOTH));
                } else {
                    thumbnail = tmpIcon;
                }
            }
        }
    
        public BufferedImage getImage(String fileName) {
            try {
                return ImageIO.read(new File(fileName));
            } catch (IOException ioe) {
                System.err.println("Error loading Image!!");
            }
            return null;
        }
    
        @Override
        public void propertyChange(final PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                if (isShowing()) {
                    new Thread(new Runnable() {
    
                        @Override
                        public void run() {
                            loadImage((File) e.getNewValue());
                            repaint();
                        }
                    }).start();
    
                }
            }
        }
    
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (thumbnail != null) {
                int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
                int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
                if (y < 0) {
                    y = 0;
                }
    
                if (x < 5) {
                    x = 5;
                }
                thumbnail.paintIcon(this, g, x, y);
            }
        }
    }

}
```

*s29.postimg.org/kfd65cy83/Process_Image.jpg

To run the program , java ProcessImage from the cmd-line or use an IDE like NetBeans to launch the program.
 From the menu File-> Open select an Image , click on the "OK" button. Now from the menu select "Blur" to blur the Image, "Emboss", to Emboss
 the Image etc.,

 For more complex Image filters see Jerry Huxtable's wonderful filters implemented in Java (Jerry's Java Image Processing Pages)

  Download the filters : Download Java Image Processing Classes

  Use them in your program!!

  Here is how to use various filters :


```
// We import various Image filters ...
  import com.jhlabs.image.*;
  ...
  // Rest of the classes
  
  // To apply the emboss filter , we use the following code
  
  // Emboss the Image (like in the back side of a Rupee coin)
      EmbossFilter eFilter = new EmbossFilter();
      eFilter.setAzimuth(5f);
      eFilter.setElevation(0.5f);
      eFilter.setBumpHeight(1.8f);
      if (image != null) {
           setImage(eFilter.filter(image, null), "Embossed - Azimuth = 5f , Elevation = 0.5f , BumpHeight = 1.8f");
      }
```
 
 Here is an example demo that uses various filters:


```
package com.jhlabs.util;
 
 /**
  * Created with IntelliJ IDEA.
  * User: Sowndar
  * Date: 8/2/14
  * Time: 8:43 PM
  * To change this template use File | Settings | File Templates.
  */
 // ImageProcessor - Do some filters like lens Blur, crystallize, Emboss, Ripple . motion blur etc.,
 import com.jhlabs.image.*;
 
 import javax.imageio.ImageIO;
 import javax.swing.*;
 import javax.swing.filechooser.FileFilter;
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.image.BufferedImage;
 import java.awt.print.PageFormat;
 import java.awt.print.Printable;
 import java.awt.print.PrinterException;
 import java.awt.print.PrinterJob;
 import java.io.File;
 import java.io.IOException;
 import java.util.HashSet;
 import java.util.Set;
 
 public class ImageProcessor extends JFrame implements ActionListener, Printable {
 
     private JLabel label = new JLabel();
     private JFileChooser fc = new JFileChooser(".");
     private JLabel message = new JLabel("Ready", JLabel.LEFT);
     private BufferedImage buffImg, image;
     // MenuItems ...
     private JMenuItem open = new JMenuItem("Open...");
     private JMenuItem revert = new JMenuItem("Revert");
     private JMenuItem lensBlur = new JMenuItem("Lens Blur");
     private JMenuItem crystallize = new JMenuItem("Crystallize");
     private JMenuItem emboss = new JMenuItem("Emboss");
     private JMenuItem motionBlur = new JMenuItem("Motion Blur");
     private JMenuItem oil = new JMenuItem("Oil");
     private JMenuItem ripple = new JMenuItem("Ripple");
     private JMenuItem sparkle = new JMenuItem("Sparkle");
     private JMenuItem twirl = new JMenuItem("Twirl");
     private JMenuItem water = new JMenuItem("Water Ripples");
     private JMenuItem print = new JMenuItem("Print");
     private JMenuItem save = new JMenuItem("Save");
     private JMenuItem exit = new JMenuItem("Exit");
     private int imgWidth = -1;
     private int imgHeight = -1;
     private Dimension scrDim;
     private String fileName;
 
     // Get supported Image formats (remove duplicate entries)
     public String[] getReaderFormats() {
         String[] rFormat = ImageIO.getReaderFormatNames();
         Set<String> set = new HashSet<String>();
         String imgformat = "";
         // Remove duplicate entries
         for (String aRFormat : rFormat) {
             imgformat = aRFormat;
             imgformat = imgformat.toLowerCase();
             set.add(imgformat);
         }
         String[] frmt = new String[set.size()];
         return set.toArray(frmt);
     }
 
     // Update the UI
     public void updateUI() {
         open.updateUI();
         revert.updateUI();
         lensBlur.updateUI();
         crystallize.updateUI();
         emboss.updateUI();
         motionBlur.updateUI();
         oil.updateUI();
         ripple.updateUI();
         sparkle.updateUI();
         twirl.updateUI();
         exit.updateUI();
         fc.updateUI();
         water.updateUI();
         print.updateUI();
         save.updateUI();
     }
 
     // Enable or disable Components
     @Override
     public void setEnabled(boolean condition) {
         revert.setEnabled(condition);
         lensBlur.setEnabled(condition);
         crystallize.setEnabled(condition);
         emboss.setEnabled(condition);
         motionBlur.setEnabled(condition);
         oil.setEnabled(condition);
         ripple.setEnabled(condition);
         sparkle.setEnabled(condition);
         twirl.setEnabled(condition);
         water.setEnabled(condition);
         print.setEnabled(condition);
         save.setEnabled(condition);
     }
 
     // Constructor
     public ImageProcessor(String title) {
         super(title);
         try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
             System.err.println("Error loading look'n feel!!");
         }
         updateUI();
         scrDim = Toolkit.getDefaultToolkit().getScreenSize();
         label.setHorizontalAlignment(SwingConstants.CENTER);
         label.setVerticalAlignment(SwingConstants.CENTER);
         open.addActionListener(this);
         revert.addActionListener(this);
         lensBlur.addActionListener(this);
         crystallize.addActionListener(this);
         emboss.addActionListener(this);
         motionBlur.addActionListener(this);
         oil.addActionListener(this);
         ripple.addActionListener(this);
         sparkle.addActionListener(this);
         twirl.addActionListener(this);
         water.addActionListener(this);
         print.addActionListener(this);
         save.addActionListener(this);
         exit.addActionListener(this);
         JMenuBar mBar = new JMenuBar();
 
         JMenu menu = new JMenu("File");
         menu.addActionListener(this);
 
         //Disable menuitems other than 'Open' & 'Exit"!
         // Since there is no Image to process!!
         setEnabled(false);
         menu.add(open);
         menu.addSeparator();
         menu.add(revert);
         menu.addSeparator();
         menu.add(print);
         menu.add(save);
         menu.add(exit);
 
         mBar.add(menu);
 
         menu = new JMenu("Filter");
         menu.addActionListener(this);
 
         menu.add(lensBlur);
         menu.add(crystallize);
         menu.add(emboss);
         menu.add(ripple);
         menu.add(motionBlur);
         menu.add(oil);
         menu.add(sparkle);
         menu.add(twirl);
         menu.add(water);
 
         mBar.add(menu);
         setJMenuBar(mBar);
 
         add(new JScrollPane(label), BorderLayout.CENTER);
         add(message, BorderLayout.SOUTH);
         setSize(scrDim.width / 2, scrDim.height);
         setVisible(true);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
     }
 
     // Print the Image
     @Override
     public int print(Graphics g, PageFormat pf, int page) throws
             PrinterException {
 
         if (page > 0) { /* We have only one page, and 'page' is zero-based */
 
             return NO_SUCH_PAGE;
         }
 
         /* User (0,0) is typically outside the imageable area, so we must
          * translate by the X and Y values in the PageFormat to avoid clipping
          */
         Graphics2D g2d = (Graphics2D) g;
         g2d.translate(pf.getImageableX(), pf.getImageableY());
 
         if (buffImg != null) {
             g2d.drawImage(buffImg, 0, 0, this);
         }
 
         /* tell the caller that this page is part of the printed document */
         return PAGE_EXISTS;
     }
 
     // Update the Image in the label & the message
     public void setImage(BufferedImage buff, String msg) {
         if (buff != null) {
             if (label != null) {
                 label.setIcon(new ImageIcon(buff));
                 buffImg = buff;
                 message.setText(msg);
             }
         }
     }
 
     // Get the Image from the disk
     public BufferedImage getImage(String fileName) {
         //Fetch the Image for processing
         try {
             return ImageIO.read(new File(fileName));
         } catch (IOException ioe) {
             JOptionPane.showMessageDialog(null, "Not a valid Image!!!", "Error", JOptionPane.ERROR_MESSAGE);
             //Disable menuitems other than 'Open' & 'Exit"!
             // Since there is no Image to process!!
             setEnabled(false);
         }
         // In case of error
         return null;
     }
 
     // Save Image to the disk
     public void saveImage() {
         try
         {
             String format = fileName.substring(fileName.lastIndexOf(".")+1);
             ImageIO.write(buffImg, format, new File(fileName));
 
         } catch (IOException ioe) {
             JOptionPane.showMessageDialog(null,"The Image can't be saved!!", "Message", JOptionPane.ERROR_MESSAGE);
         }
     }
 
     @Override
     public void actionPerformed(ActionEvent ae) {
         Object source = ae.getSource();
         if (source == exit) {
             System.exit(0);
         } else if(source == save) {
             saveImage();
         }
         else if(source == print) {
             if (image != null) {
                 // Print the Image
                 PrinterJob job = PrinterJob.getPrinterJob();
                 job.setPrintable(this);
                 boolean ok = job.printDialog();
                 if (ok) {
                     try {
                         job.print();
                     } catch (PrinterException ex) {
                         /* The job did not successfully complete */
                     }
                 }
             }
         }
         else if (source == revert) {
             // Restore the original Image
             label.setIcon(new ImageIcon(image));
             message.setText("Image Reverted");
         } else if (source == open) {
             //Open the FileChooser dialog
             fc.setAccessory(new ImagePreview(fc));
             fc.setPreferredSize(new Dimension(800, 550));
             fc.setAcceptAllFileFilterUsed(false);
             fc.setCurrentDirectory(new File("Samples"));
             final String[] format = getReaderFormats();
             fc.addChoosableFileFilter(new FileFilter() {
 
                 @Override
                 public boolean accept(File file) {
                     String fileName = file.getName();
                     for (String aFormat : format) {
                         // Show directory & images files only
                         if (fileName.endsWith(aFormat) || file.isDirectory()) {
                             return true;
                         }
                     }
                     return false;
                 }
 
                 // Show something like "*.jpg,*.jpeg,*.bmp,*.tiff,*.gif,*.jpeg2000" etc.,
                 @Override
                 public String getDescription() {
                     String str = "";
                     for (String aFormat : format) {
                         str += "*." + aFormat + ",";
                     }
                     return str;
                 }
             });
             int result = fc.showOpenDialog(this);
 
             if (result != 0) {
                 return;
             }
 
             File file = fc.getSelectedFile();
             fileName = file.toString();
             if (file == null) {
                 return;
             } else {
                 //Fetch the Image for processing
                 image = getImage(fileName);
                 if(image != null) {
                     buffImg = image;
                     imgWidth = image.getWidth(null);
                     imgHeight = image.getHeight(null);
                     //Enable the MenuItems now!
                     setEnabled(true);
                     // Update the label
                     label.setIcon(new ImageIcon(buffImg));
                     message.setText("Ready");
                     pack();
                 }
                 else {
                     setEnabled(false);
                     // Update the label
                     label.setIcon(null);
                     message.setText("Ready");
                 }
             }
         } else if (source == lensBlur) {
             new Thread(new Runnable() {
 
                 @Override
                 public void run() {
                     setEnabled(false);
                     LensBlurFilter lFilter = new LensBlurFilter();
                     lFilter.setBloom(1f);
                     lFilter.setBloomThreshold(5f);
                     lFilter.setRadius(15);
                     if (image != null) {
                         setImage(lFilter.filter(image, null), "Lens Blur - Bloom = 1f, BloomThreshold = 5f, Radius = 15");
                     }
                     setEnabled(true);
                 }
             }).start();
 
         } else if (source == crystallize) {
             new Thread(new Runnable() {
 
                 @Override
                 public void run() {
                     setEnabled(false);
                     CrystallizeFilter cFilter = new CrystallizeFilter();
                     cFilter.setAmount(40f);
                     cFilter.setGridType(CrystallizeFilter.HEXAGONAL);
                     cFilter.setScale(20);
                     if (image != null) {
                         setImage(cFilter.filter(image, null), "Crystallized - Amount = 40f , Scale = 20");
                     }
                     setEnabled(true);
                 }
             }).start();
 
         } else if (source == oil) {
             // This takes a bit longer to process
             new Thread(new Runnable() {
 
                 @Override
                 public void run() {
                     setEnabled(false);
                     OilFilter oFilter = new OilFilter();
                     if (image != null) {
                         setImage(oFilter.filter(image, null), "Image Oil Filter");
                     }
                     setEnabled(true);
                 }
             }).start();
 
         } else if (source == ripple) {
             try {
                 setEnabled(false);
                 RippleFilter rFilter = new RippleFilter();
                 // WaveType - SINE, SAWTOOTH, TRIANGLE, NOISE
                 rFilter.setWaveType(RippleFilter.SINE);
                 rFilter.setXAmplitude(5f);
                 rFilter.setYAmplitude(5f);
                 rFilter.setXWavelength(6f);
                 if (image != null) {
                     setImage(rFilter.filter(image, null), "Ripples - WaveType = SINE, XAmplitude = 5f, YAmplitude = 5f, XWaveLength = 6f");
                 }
                 setEnabled(true);
             } catch (Exception e) {
             }
         } else if (source == sparkle) {
             new Thread(new Runnable() {
 
                 @Override
                 public void run() {
                     setEnabled(false);
                     SparkleFilter spFilter = new SparkleFilter();
                     spFilter.setAmount(40);
                     spFilter.setRadius(50);
                     spFilter.setRandomness(10 * 2);
                     spFilter.setRays(55);
                     if (image != null) {
                         setImage(spFilter.filter(image, null), "Sparkle");
                     }
                     setEnabled(true);
                 }
             }).start();
 
         } else if (source == emboss) {
             setEnabled(false);
             // Emboss the Image (like in the back side of a Rupee coin)
             EmbossFilter eFilter = new EmbossFilter();
             eFilter.setAzimuth(5f);
             eFilter.setElevation(0.5f);
             eFilter.setBumpHeight(1.8f);
             if (image != null) {
                 setImage(eFilter.filter(image, null), "Embossed - Azimuth = 5f , Elevation = 0.5f , BumpHeight = 1.8f");
             }
             setEnabled(true);
 
         } else if (source == motionBlur) {
             new Thread(new Runnable() {
 
                 @Override
                 public void run() {
                     // Motion blur takes a lot of time!!, For faster Motion blur use MotionBlurOp
                     setEnabled(false);
                     MotionBlurFilter mFilter = new MotionBlurFilter();
                     mFilter.setDistance(120);
                     mFilter.setAngle(20);
                     if (image != null) {
                         setImage(mFilter.filter(image, null), "Motion Blur - Angle = 120f");
                     }
                     setEnabled(true);
                 }
             }).start();
 
         } else if(source == twirl) {
             setEnabled(false);
             TwirlFilter tFilter = new TwirlFilter();
             tFilter.setAngle(3);
             tFilter.setRadius(250f);
             if (image != null) {
                 setImage(tFilter.filter(image, null), "Twirl - Angle = 3 radians");
             }
             setEnabled(true);
         }
         else
         {
             setEnabled(false);
             // Water ripple effect
             WaterFilter wFilter = new WaterFilter();
             wFilter.setAmplitude(20);
             wFilter.setPhase(8f);
             wFilter.setWavelength(120f);
             wFilter.setRadius(250f);
             if (image != null) {
                 setImage(wFilter.filter(image, null), "Water Ripples - Amplitude = 20, Phase = 8f, WaveLength = 120f, Radius = 250f");
             }
             setEnabled(true);
         }
     }
 
     public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
 
             @Override
             public void run() {
                 new ImageProcessor("Image Processor");
             }
         });
     }
 }
```

 *s29.postimg.org/rm9t442tf/Image_Processor.jpg

 Here is the code for ImagePreview.java


```
package com.jhlabs.util;
 
 /**
  * Created with IntelliJ IDEA.
  * User: Sowndar
  * Date: 8/2/14
  * Time: 8:45 PM
  * To change this template use File | Settings | File Templates.
  */
 
 import javax.imageio.ImageIO;
 import javax.swing.*;
 import javax.swing.border.BevelBorder;
 import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 import java.io.File;
 import java.io.IOException;
 
 /**
  *
  * @author Sowndar
  */
 public class ImagePreview extends JComponent implements PropertyChangeListener {
 
     ImageIcon thumbnail = null;
     int width = 180;
 
     public ImagePreview(JFileChooser fc) {
         setPreferredSize(new Dimension(width, 50));
         fc.addPropertyChangeListener(this);
         setBorder(new BevelBorder(BevelBorder.LOWERED));
     }
 
     public void loadImage(File f) {
         if (f == null) {
             thumbnail = null;
         } else {
             ImageIcon tmpIcon = new ImageIcon(getImage(f.getPath()));
             if (tmpIcon.getIconWidth() > width) {
                 thumbnail = new ImageIcon(
                         tmpIcon.getImage().getScaledInstance(width, -1, Image.SCALE_SMOOTH));
             } else {
                 thumbnail = tmpIcon;
             }
         }
     }
 
     public BufferedImage getImage(String fileName) {
         try {
             return ImageIO.read(new File(fileName));
         } catch (IOException ioe) {
             System.err.println("Error loading Image!!");
         }
         return null;
     }
 
     @Override
     public void propertyChange(PropertyChangeEvent e) {
         String prop = e.getPropertyName();
         if (prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
             if (isShowing()) {
                 loadImage((File) e.getNewValue());
                 repaint();
             }
         }
     }
 
     @Override
     public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (thumbnail != null) {
             int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
             int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
             if (y < 0) {
                 y = 0;
             }
 
             if (x < 5) {
                 x = 5;
             }
             thumbnail.paintIcon(this, g, x, y);
         }
     }
 }
```
 
 See the complete guide to *Image Processing in Java* link : *www.digit.in/forum/programming/186791-image-processing-java.html

*How do I scale up or scale down an Image in Java?*

  Use the getScaledInstance() method in the Image class.

  For eg., Image image = ... // get the Image

  int width = image.getWidth(null);
  int height = image.getHeight(null);

  // This scales the Image to 2x (ie., 200%) times of the original

  image = image.getScaledInstance(width*2, height*2, Image.SCALE_SMOOTH);

  The image hints are SCALE_AREA_AVERAGING, SCALE_DEFAULT, SCALE_FAST, SCALE_REPLICATE, SCALE_SMOOTH.
  The Image hint SCALE_SMOOTH gives you the best image smoothness.

  Here is a demo that scales the Image to 200%


```
public class ScaleImage extends JFrame {
  
      private Image image;
      private JLabel label = new JLabel();
  
      public ScaleImage() {
          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
          }
          label.setHorizontalAlignment(SwingConstants.CENTER);
          label.setVerticalAlignment(SwingConstants.CENTER);
          //Get the Image
          image = getImage("Images/Katrina Kaif.jpg");
          if(image != null) {
              // Scale the Image to 200%
              image = image.getScaledInstance(image.getWidth(this)*2, image.getHeight(this)*2, Image.SCALE_SMOOTH);
              label.setIcon(new ImageIcon(image));
              add(new JScrollPane(label));
          }
          setTitle("ScaleImage");
          pack();
          setVisible(true);
          setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      }
  
      public Image getImage(String filename) {
          try
          {
              return ImageIO.read(new File(filename));
          } catch (IOException ioe) {
              System.err.println("Error loading Image!!");
              System.exit(-1);
          }
          return null;
      }
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
              @Override
              public void run() {
                  new ScaleImage();
              }
          });
      }
  }
```

  *s30.postimg.org/8dvkgb3e5/Scale_Image.jpg

 Q) How can I read , write to a ZIP file?

 Ans. The package "java.util.zip" contains classes to read/write a ZIP file in Java.
      The following program creates a ZIP archive using the contents of the directory "Images", Lists the contents of the zip file.
      Atlast extracts the ZIP file.



```
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author JGuru
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ZipDemo extends JFrame {

    private JTextArea area = new JTextArea();
    private static final int BUFFER = 2048;
    private String path = "Images2/";
    private String[] name;
    private String currentDir;
    private String separator;

    public ZipDemo() {
        area.setFont(new Font("Courier", Font.BOLD, 14));
        area.setForeground(Color.green);
        area.setBackground(Color.black);
        add(new JScrollPane(area), BorderLayout.CENTER);
        print("Creating ZIP file");
        print("==============================");
        createZip("Images.zip");
        print("Listing Zip contents");
        print("===============================");
        list("Images.zip");
        print("Extracting Zip file: ");
        print("================================");
        extract("Images.zip");
        setTitle("Zip Demo");
        setSize(550, 500);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void createZip(String outFile) {
        try {
            name = new File(path).list(new FilenameFilter() {

                String[] readFotmat = ImageIO.getReaderFormatNames();

                @Override
                public boolean accept(File dir, String name) {
                    for (int i = 0; i < readFotmat.length; i++) {
                        if (name.endsWith(readFotmat[i])) {
                            return true;
                        }
                    }
                    return false;
                }
            });
            String inputFile = "";
            currentDir = System.getProperty("user.dir");
            separator = System.getProperty("file.separator");
            // Create a File called "Images.zip"
            String outputFile = currentDir + separator + outFile;
            FileInputStream in = null;
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
            for (int i = 0; i < name.length; i++) {
                inputFile = path + name[i];
                in = new FileInputStream(inputFile);
                //We want just the Name!(not the directory structure in the destination directory!)
                inputFile = name[i];
                //Add the ZIP entry to the output stream
                out.putNextEntry(new ZipEntry(inputFile));
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            out.closeEntry();
            out.close();
            in.close();
        } catch (IOException ioe) {
            System.err.println("Error writing the ZIP file!");
        }
    }

    public void extract(String fileName) {
        //Decompressing a File
        currentDir = System.getProperty("user.dir");
        separator = System.getProperty("file.separator");
        try {
            File inputFile = new File(currentDir + separator + "Images.zip");
            if (!inputFile.exists()) {
                System.err.println("The specified file doesn't exist!!");
                System.exit(1);
            }
            //Get the Zip file entries first!
            ZipFile zf = null;
            try {
                zf = new ZipFile(inputFile);
            } catch (IOException e) {
            }
            Vector<String> vector = new Vector<>();

            for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                vector.addElement(((ZipEntry) entries.nextElement()).getName());
            }
            int MAX = vector.size();
            File[] outputFile = new File[MAX];
            try (ZipInputStream in = new ZipInputStream(new FileInputStream(inputFile))) {
                OutputStream out = null;

                ZipEntry entry;
                byte[] buf = new byte[1024];
                int len;
                int i = 0;
                File dest = new File(currentDir + separator + "Extract");
                // If the destination directory doesn't exist then create it
                if (!dest.exists()) {
                    dest.mkdir();
                }

                while ((entry = in.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        //Create that directory in the destination directory also!
                        File dir = new File(currentDir + separator + "Extract" + separator + entry.getName());
                        dir.mkdir();
                    } else {
                        outputFile[i] = new File(currentDir + separator + "Extract" + separator + entry.getName());
                        print("Extracting : " + entry.getName());
                        out = new FileOutputStream(outputFile[i]);

                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        i++;
                    }
                }
                out.close();
            }

        } catch (IOException ioe) {
            System.err.println("Error decompressing the zip file!");
        }
    }

    public void list(String fileName) {
        //Listing the Contents of a ZIP File
        try {
            ZipFile zf = new ZipFile(fileName);
            for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {

                print(((ZipEntry) entries.nextElement()).getName());
            }
        } catch (IOException e) {
            System.err.println("Error processing Zip file!!");
        }
    }

    public void print(String str) {
        area.append(str + "\n");
    }

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

            @Override
            public void run() {
                new ZipDemo();
            }
        });
    }
}
```
 
*What Image formats does Java support?*

  Java Supports JPEG, BMP, PNG, GIF .
  You can get additional Image support using JAI_ImageIO package
  After installing JAI_ImageIO package you will get TIFF, JPEG-LOSSLESS, RAW, JPEG 2000 Wireless BitMap etc.,
  Since JAI_ImageIO is available for 32-bit JDK, copy the file 'jai_imageio.jar' to the ext folder of the 64-bit JDK.


```
//Get available file formats for Image I/O
  import java.util.Arrays;
  import java.util.HashSet;
  import java.util.Set;
  import javax.imageio.*;
  
  public class GetFormats {
  
      public static void main(String args[]) {
  
          String readFormats[] = ImageIO.getReaderFormatNames();
          String writeFormats[] = ImageIO.getWriterFormatNames();
          String tmp = "";
          Set<String> rset = new HashSet<>();
          Set<String> wset = new HashSet<>();
  
          for (int i = 0; i < readFormats.length; i++) {
              tmp = readFormats[i];
              //Change it to lowercase
              tmp = tmp.toLowerCase();
              rset.add(tmp);
          }
  
          for (int i = 0; i < writeFormats.length; i++) {
              tmp = writeFormats[i];
              tmp = tmp.toLowerCase();
              wset.add(tmp);
          }
          System.out.println("Readers: " + Arrays.asList(rset));
          System.out.println("Writers: " + Arrays.asList(wset));
      }
}
```
 
  Here is demo that shows how to use Java ImageIO class to load a Image & display it.


```
import java.awt.*;
  import java.awt.image.BufferedImage;
  import java.io.File;
  import java.io.IOException;
  import javax.imageio.ImageIO;
  import javax.swing.*;
  
  public class ImageIODemo extends JPanel {
  
      private BufferedImage buffImage;
      private String fileName = "Images/Katrina Kaif.jpg";
  
      public ImageIODemo() {
          buffImage = getImage(fileName);
          setPreferredSize(new Dimension(buffImage.getWidth(), buffImage.getHeight()));
      }
  
      public BufferedImage getImage(String fileName) {
          try {
              return ImageIO.read(new File(fileName));
          } catch (IOException ioe) {
              System.err.println("Error loading Image!!");
          }
          return null;
      }
  
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g;
          // Set the rendering hints
          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);
          // Draw the Image
          if (buffImage != null) {
              g2d.drawImage(buffImage, 0, 0, this);
          }
      }
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
  
              @Override
              public void run() {
                  JFrame f = new JFrame("ImageIO Demo");
                  f.add(new ImageIODemo());
                  f.pack();
                  f.setVisible(true);
                  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              }
          });
      }
  }
```

  *s11.postimg.org/wvcndbk8v/Image_IODemo.jpg

*How do I search for a particular word in a text document?*

As you type characters in the text field the program searches for the typed text in the text area. If the entry is found it gets highlighted. If the program fails to find the entry then the text field's background becomes pink. A status bar below the text area displays a message whether text is found or not. The Escape key is used to start a new search or to finish the current one.



```
To highlight text, this example uses a highlighter and a painter. The code below creates and sets up the highlighter and the painter for the text area.

    final Highlighter hilit;
    final Highlighter.HighlightPainter painter;
    ...
    hilit = new DefaultHighlighter();
    painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
    textArea.setHighlighter(hilit);

This code adds a document listener to the text field's document.

    entry.getDocument().addDocumentListener(this);

Document listener's insertUpdate and removeUpdate methods call the search method, which not only performs a search in the text area but also handles highlighting. The following code highlights the found text, sets the caret to the end of the found match, sets the default background for the text field, and displays a message in the status bar.

    hilit.addHighlight(index, end, painter);
    textArea.setCaretPosition(end);
    entry.setBackground(entryBg);
    message("'" + s + "' found. Press ESC to end search");

The status bar is a JLabel object. The code below shows how the message method is implemented.

    private JLabel status;
    ...
    void message(String msg) {
        status.setText(msg);
    }

If there is no match in the text area, the following code changes the text field's background to pink and displays a proper information message.

    entry.setBackground(ERROR_COLOR);
    message("'" + s + "' not found. Press ESC to start a new search");

The CancelAction class is responsible for handling the Escape key as follows.

       class CancelAction extends AbstractAction {
           public void actionPerformed(ActionEvent ev) {
                   hilit.removeAllHighlights();
                   entry.setText("");
                   entry.setBackground(entryBg);
               }
       }
```


```
/*
 * TextFieldDemo.java requires one additional file:
 * content.txt
 */

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.*;

public class TextFieldDemo extends JFrame
                           implements DocumentListener {
    
    private JTextField entry;
    private JLabel jLabel1;
    private JScrollPane jScrollPane1;
    private JLabel status;
    private JTextArea textArea;
    
    final static Color  HILIT_COLOR = Color.LIGHT_GRAY;
    final static Color  ERROR_COLOR = Color.PINK;
    final static String CANCEL_ACTION = "cancel-search";
    
    final Color entryBg;
    final Highlighter hilit;
    final Highlighter.HighlightPainter painter;
    
    
    public TextFieldDemo() {
        initComponents();
        
        InputStream in = getClass().getResourceAsStream("content.txt");
        try {
            textArea.read(new InputStreamReader(in), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        hilit = new DefaultHighlighter();
        painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
        textArea.setHighlighter(hilit);
        
        entryBg = entry.getBackground();
        entry.getDocument().addDocumentListener(this);
        
        InputMap im = entry.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap am = entry.getActionMap();
        im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
        am.put(CANCEL_ACTION, new CancelAction());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     */

    private void initComponents() {
        entry = new JTextField();
        textArea = new JTextArea();
        status = new JLabel();
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("TextFieldDemo");

        textArea.setColumns(20);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        jScrollPane1 = new JScrollPane(textArea);

        jLabel1.setText("Enter text to search:");

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        
	//Create a parallel group for the horizontal axis
	ParallelGroup hGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
	
	//Create a sequential and a parallel groups
	SequentialGroup h1 = layout.createSequentialGroup();
	ParallelGroup h2 = layout.createParallelGroup(GroupLayout.Alignment.TRAILING);
	
	//Add a container gap to the sequential group h1
	h1.addContainerGap();
	
	//Add a scroll pane and a label to the parallel group h2
	h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
	h2.addComponent(status, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
	
	//Create a sequential group h3
	SequentialGroup h3 = layout.createSequentialGroup();
	h3.addComponent(jLabel1);
	h3.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
	h3.addComponent(entry, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE);
	 
	//Add the group h3 to the group h2
	h2.addGroup(h3);
	//Add the group h2 to the group h1
	h1.addGroup(h2);

	h1.addContainerGap();
	
	//Add the group h1 to the hGroup
	hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
	//Create the horizontal group
	layout.setHorizontalGroup(hGroup);
	
        
	//Create a parallel group for the vertical axis
	ParallelGroup vGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
	//Create a sequential group v1
	SequentialGroup v1 = layout.createSequentialGroup();
	//Add a container gap to the sequential group v1
	v1.addContainerGap();
	//Create a parallel group v2
	ParallelGroup v2 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
	v2.addComponent(jLabel1);
	v2.addComponent(entry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE);
	//Add the group v2 tp the group v1
	v1.addGroup(v2);
	v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
	v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE);
	v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
	v1.addComponent(status);
	v1.addContainerGap();
	
	//Add the group v1 to the group vGroup
	vGroup.addGroup(v1);
	//Create the vertical group
	layout.setVerticalGroup(vGroup);
	pack();
    }

    public void search() {
        hilit.removeAllHighlights();
        
        String s = entry.getText();
        if (s.length() <= 0) {
            message("Nothing to search");
            return;
        }
        
        String content = textArea.getText();
        int index = content.indexOf(s, 0);
        if (index >= 0) {   // match found
            try {
                int end = index + s.length();
                hilit.addHighlight(index, end, painter);
                textArea.setCaretPosition(end);
                entry.setBackground(entryBg);
                message("'" + s + "' found. Press ESC to end search");
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        } else {
            entry.setBackground(ERROR_COLOR);
            message("'" + s + "' not found. Press ESC to start a new search");
        }
    }

    void message(String msg) {
        status.setText(msg);
    }

    // DocumentListener methods
    
    public void insertUpdate(DocumentEvent ev) {
        search();
    }
    
    public void removeUpdate(DocumentEvent ev) {
        search();
    }
    
    public void changedUpdate(DocumentEvent ev) {
    }
    
    class CancelAction extends AbstractAction {
        public void actionPerformed(ActionEvent ev) {
            hilit.removeAllHighlights();
            entry.setText("");
            entry.setBackground(entryBg);
        }
    }
    
    
    public static void main(String args[]) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
	SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE);
		new TextFieldDemo().setVisible(true);
            }
        });
    }
    
   
}
```

*content.txt*


```
ALICE'S ADVENTURES IN WONDERLAND
by Lewis Carroll

CHAPTER I
DOWN THE RABBIT-HOLE
ALICE was beginning to get very tired of sitting by her sister on the bank and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?"

So she was considering, in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.

There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself "Oh dear! Oh dear! I shall be too late!" (when she thought it over afterwards it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but, when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and was just in time to see it pop down a large rabbit-hole under the hedge.

In another moment down went Alice after it, never once considering how in the world she was to get out again.

The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down what seemed to be a very deep well.


Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her, and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything: then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves: here and there she saw maps and pictures hung upon pegs. She took down ajar from one of the shelves as she passed: it was labeled "ORANGE MARMALADE" but to her great disappointment it was empty: she did not like to drop the jar, for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.

"Well!" thought Alice to herself "After such a fall as this, I shall think nothing of tumbling down-stairs! How brave they'll all think me at home! Why, I wouldn't say anything about it, even if I fell off the top of the house!" (which was very likely true.)

Down, down, down. Would the fall never come to an end? "I wonder how many miles I've fallen by this time?" she said aloud. "I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think-" (for, you see, Alice had learnt several things of this sort in her lessons in the school-room, and though this was not a very good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) "-- yes that's about the right distance -- but then I wonder what Latitude or Longitude I've got to?" (Alice had not the slightest idea what Latitude was, or Longitude either, but she thought they were nice grand words to say.)

Presently she began again. "I wonder if I shall fall fight through the earth! How funny it'll seem to come out among the people that walk with their heads downwards! The antipathies, I think-" (she was rather glad there was no one listening, this time, as it didn't sound at all the right word) "-but I shall have to ask them what the name of the country is, you know. Please, Ma'am, is this New Zealand? Or Australia?" (and she tried to curtsey as she spoke- fancy, curtseying as you're falling through the air! Do you think you could manage it?) "And what an ignorant little girl she'll think me for asking! No, it'll never do to ask: perhaps I shall see it written up somewhere."

Down, down, down. There was nothing else to do, so Alice soon began talking again. "Dinah'll miss me very much to-night, I should think!" (Dinah was the cat.) "I hope they'll remember her saucer of milk at tea-time. Dinah, my dear! I wish you were down here with me! There are no mice in the air, I'm afraid, but you might catch a bat, and that's very like a mouse, you know. But do cats eat bats, I wonder?" And here Alice began to get rather sleepy, and went on saying to herself, in a dreamy son of way, "Do cats eat bats? Do cats eat bats?" and sometimes "Do bats eat cats?" for, you see, as she couldn't answer either question, it didn't much matter which way she put it. She felt that she was dozing off, and had just begun to dream that she was walking hand in hand with Dinah, and was saying to her, very earnestly, "Now, Dinah, tell me the truth: did you ever eat a bat?" when suddenly, thump! thump! down she came upon a heap of sticks and dry leaves, and the fall was over.

Alice was not a bit hurt, and she jumped up on to her feet in a moment: she looked up, but it was all dark overhead: before her was another long passage, and the White Rabbit was still in sight, hurrying down it. There was not a moment to be lost: away went Alice like the wind, and was just in time to hear it say, as it turned a comer, "Oh my ears and whiskers, how late it's getting!" She was close behind it when she turned the comer, but the Rabbit was no longer to be seen: she found herself in a long, low hall, which was lit up by a row of lamps hanging from the roof.

There were doors all round the hall, but they were all locked; and when Alice had been all the way down one side and up the other, trying every door, she walked sadly down the middle, wondering how she was ever to get out again.

Suddenly she came upon a little three-legged table, all made of solid glass: there was nothing on it but a tiny golden key, and Alice's first idea was that this might belong to one of the doors of the hall; but, alas! either the locks were too large, or the key was too small, but at any rate it would not open any of them. However, on the second time round, she came upon a low curtain she had not noticed before, and behind it was a little door about fifteen inches high: she tried the little golden key in the lock, and to her great delight it fitted!

Alice opened the door and found that it led into a small passage, not much larger than a rat-hole: she knelt down and looked along the passage into the loveliest garden you ever saw. How she longed to get out of that dark hall, and wander about among those beds of bright flowers and those cool fountains, but she could not even get her head through the doorway; "and even if my head would go through," thought poor Alice, "it would be of very little use without my shoulders. Oh, how I wish I could shut up like a telescope! I think I could, if I only knew how to begin." For, you see, so many out-of-the- way things had happened lately, that Alice had begun to think that very few things indeed were really impossible.

There seemed to be no use in waiting by the little door, so she went back to the table, half hoping she might find another key on it, or at any rate a book of rules for shutting people up like telescopes: this time she found a little bottle on it, ("which certainly was not here before," said Alice), and tied round the neck of the bottle was a paper label, with the words "DRINK ME" beautifully printed on it in large letters.It was all very well to say "Drink me," but the wise little Alice was not going to do that in a hurry. "No, I'll look first," she said, "and see whether it's marked 'poison' or not"; for she had read several nice little stories about children who had got burnt, and eaten up by wild beasts, and other unpleasant things, all because they would not remember the simple rules their friends had taught them: such as, that a red-hot poker will burn you if you hold it too long; and that, if you cut your finger very deeply with a knife, it usually bleeds; and she had never forgotten that, if you drink much from a bottle marked "poison," it is almost certain to disagree with you, sooner or later.However, this bottle was not marked "poison," so Alice ventured to taste it, and, finding it very nice (it had, in fact, a sort of mixed flavour of cherry-tart, custard, pine-apple, roast turkey, toffy, and hot buttered toast), she very soon finished it off.

"What a curious feeling!" said Alice. "I must be shutting up like a telescope!"

And so it was indeed: she was now only ten inches high, and her face brightened up at the thought that she was now the right size for going through the little door into that lovely garden. First, however, she waited for a few minutes to see if she was going to shrink any further: she felt a little nervous about this; "for it might end, you know," said Alice to herself; "in my going out altogether, like a candle. I wonder what I should be like then?" And she tried to fancy what the flame of a candle looks like after the candle is blown out, for she could not remember ever having seen such a thing.

After a while, finding that nothing more happened, she decided on going into the garden at once; but, alas for poor Alice! when she got to the door, she found she had forgotten the little golden key, and when she went back to the table for it, she found she could not possibly reach it: she could see it quite plainly through the glass, and she tried her best to climb up one of the legs of the table, but it was too slippery; and when she had tired herself out with trying, the poor little thing sat down and cried.

"Come, there's no use in crying like that!" said Alice to herself rather sharply. "I advise you to leave off this minute!" She generally gave herself very good advice (though she very seldom followed it), and sometimes she scolded herself so severely as to bring tears into her eyes; and once she remembered trying to box her own ears for having cheated herself in a game of croquet she was playing against herself, for this curious child was very fond of pretending to be two people. "But it's no use now," thought poor Alice, "to pretend to be two people! Why, there's hardly enough of me left to make one respectable person!"

Soon her eye fell on a little glass box that was lying under the table: she opened it, and found in it a very small cake, on which the words "EAT ME" were beautifully marked in currants. "Well, I'll eat it," said Alice, "and if it makes me grow larger, I can reach the key; and if it makes me grow smaller, I can creep under the door: so either way I'll get into the garden, and I don't care which happens!"

She ate a little bit, and said anxiously to herself "Which way? Which way?", holding her hand on the top of her head to feel which way it was growing; and she was quite surprised to find that she remained the same size. To be sure, this is what generally happens when one eats cake; but Alice had got so much into the way of expecting nothing but out-of-the-way things to happen, that it seemed quite dull and stupid for life to go on in the common way.

So she set to work, and very soon finished off the cake.
```

 Store it in a file called "content.txt" in the current directory.

  Launch the program. Type some word (for eg., "was") this program searches the text as you type in the words. Press ESC button to stop searching.


*How do I display the File system in JTree in Java?*

 JTree is a slightly complex class. You need to understand DefaultMutableTreeNode.
 Here is one example of FileSystem. It loads the C Drive or root (/) in Linux, Solaris, Mac OS. It shows the files & directories.

*FileTreeFrame.java*

```
// FileTreeFrame.java 
  import java.io.File;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileTreeFrame extends JFrame {
  private JTree fileTree;

  private FileSystemModel fileSystemModel;

  private JTextArea fileDetailsTextArea = new JTextArea();

  public FileTreeFrame(String directory) {
    super("JTree FileSystem Viewer");
    fileDetailsTextArea.setEditable(false);
    fileSystemModel = new FileSystemModel(new File(directory));
    fileTree = new JTree(fileSystemModel);
    fileTree.setEditable(true);
    fileTree.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent event) {
        File file = (File) fileTree.getLastSelectedPathComponent();
        fileDetailsTextArea.setText(getFileDetails(file));
      }
    });
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, new JScrollPane(
        fileTree), new JScrollPane(fileDetailsTextArea));
    getContentPane().add(splitPane);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(640, 480);
    setVisible(true);
  }

  private String getFileDetails(File file) {
    if (file == null)
      return "";
    StringBuffer buffer = new StringBuffer();
    buffer.append("Name: " + file.getName() + "\n");
    buffer.append("Path: " + file.getPath() + "\n");
    buffer.append("Size: " + file.length() + "\n");
    return buffer.toString();
  }

  public static void main(String args[]) {
    new FileTreeFrame("c:\\");
  }
}

class FileSystemModel implements TreeModel {
  private File root;

  private Vector listeners = new Vector();

  public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
  }

  public Object getRoot() {
    return root;
  }

  public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
  }

  public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
      String[] fileList = file.list();
      if (fileList != null)
        return file.list().length;
    }
    return 0;
  }

  public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
  }

  public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
      if (file.getName().equals(children[i])) {
        return i;
      }
    }
    return -1;

  }

  public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);

  }

  private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
      listener = (TreeModelListener) iterator.next();
      listener.treeNodesChanged(event);
    }
  }

  public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
  }

  public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
  }

  private class TreeFile extends File {
    public TreeFile(File parent, String child) {
      super(parent, child);
    }

    public String toString() {
      return getName();
    }
  }
}
```

 Here is another demo of the FileSystem that shows only directories. It shows the entire FileSystem.
*FileSystemDemo2.java*

```
// FileSystemDemo2.java
 import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

public class FileSystemDemo2 extends JFrame {

    public static final ImageIcon ICON_COMPUTER
            = new ImageIcon("Images/My Computer.png");
    public static final ImageIcon ICON_DISK
            = new ImageIcon("Images/HardDrive.png");
    public static final ImageIcon ICON_FOLDER
            = new ImageIcon("Images/folder_closed.png");
    public static final ImageIcon ICON_EXPANDEDFOLDER
            = new ImageIcon("Images/folder_open.png");

    protected JTree m_tree;
    protected DefaultTreeModel m_model;
    protected JTextField m_display;

    public FileSystemDemo2() {
        super("Directories Tree");
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(scrDim.width/2, scrDim.height/2);

        DefaultMutableTreeNode top = new DefaultMutableTreeNode(
                new IconData(ICON_COMPUTER, null, "Computer"));

        DefaultMutableTreeNode node;
        File[] roots = File.listRoots();
        for (int k = 0; k < roots.length; k++) {
            node = new DefaultMutableTreeNode(new IconData(ICON_DISK,
                    null, new FileNode(roots[k])));
            top.add(node);
            node.add(new DefaultMutableTreeNode(new Boolean(true)));
        }

        m_model = new DefaultTreeModel(top);
        m_tree = new JTree(m_model);

        m_tree.putClientProperty("JTree.lineStyle", "Angled");

        TreeCellRenderer renderer = new IconCellRenderer();
        m_tree.setCellRenderer(renderer);

        m_tree.addTreeExpansionListener(new DirExpansionListener());

        m_tree.addTreeSelectionListener(new DirSelectionListener());

        m_tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
        m_tree.setShowsRootHandles(true);
        m_tree.setEditable(false);

        JScrollPane scroller = new JScrollPane();
        scroller.getViewport().add(m_tree);
        add(scroller, BorderLayout.CENTER);

        m_display = new JTextField();
        m_display.setEditable(false);
        add(m_display, BorderLayout.SOUTH);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    DefaultMutableTreeNode getTreeNode(TreePath path) {
        return (DefaultMutableTreeNode) (path.getLastPathComponent());
    }

    FileNode getFileNode(DefaultMutableTreeNode node) {
        if (node == null) {
            return null;
        }
        Object obj = node.getUserObject();
        if (obj instanceof IconData) {
            obj = ((IconData) obj).getObject();
        }
        if (obj instanceof FileNode) {
            return (FileNode) obj;
        } else {
            return null;
        }
    }

    // Make sure expansion is threaded and updating the tree model
    // only occurs within the event dispatching thread.
    class DirExpansionListener implements TreeExpansionListener {

        public void treeExpanded(TreeExpansionEvent event) {
            final DefaultMutableTreeNode node = getTreeNode(
                    event.getPath());
            final FileNode fnode = getFileNode(node);

            Thread runner = new Thread() {
                public void run() {
                    if (fnode != null && fnode.expand(node)) {
                        Runnable runnable = new Runnable() {
                            public void run() {
                                m_model.reload(node);
                            }
                        };
                        SwingUtilities.invokeLater(runnable);
                    }
                }
            };
            runner.start();
        }

        public void treeCollapsed(TreeExpansionEvent event) {
        }
    }

    class DirSelectionListener
            implements TreeSelectionListener {

        public void valueChanged(TreeSelectionEvent event) {
            DefaultMutableTreeNode node = getTreeNode(
                    event.getPath());
            FileNode fnode = getFileNode(node);
            if (fnode != null) {
                m_display.setText(fnode.getFile().
                        getAbsolutePath());
            } else {
                m_display.setText("");
            }
        }
    }

    public static void main(String argv[]) {
        new FileSystemDemo2();
    }
}

class IconCellRenderer
        extends JLabel
        implements TreeCellRenderer {

    protected Color m_textSelectionColor;
    protected Color m_textNonSelectionColor;
    protected Color m_bkSelectionColor;
    protected Color m_bkNonSelectionColor;
    protected Color m_borderSelectionColor;

    protected boolean m_selected;

    public IconCellRenderer() {
        super();
        m_textSelectionColor = UIManager.getColor(
                "Tree.selectionForeground");
        m_textNonSelectionColor = UIManager.getColor(
                "Tree.textForeground");
        m_bkSelectionColor = UIManager.getColor(
                "Tree.selectionBackground");
        m_bkNonSelectionColor = UIManager.getColor(
                "Tree.textBackground");
        m_borderSelectionColor = UIManager.getColor(
                "Tree.selectionBorderColor");
        setOpaque(false);
    }

    public Component getTreeCellRendererComponent(JTree tree,
            Object value, boolean sel, boolean expanded, boolean leaf,
            int row, boolean hasFocus) {
        DefaultMutableTreeNode node
                = (DefaultMutableTreeNode) value;
        Object obj = node.getUserObject();
        setText(obj.toString());

        if (obj instanceof Boolean) {
            setText("Retrieving data...");
        }

        if (obj instanceof IconData) {
            IconData idata = (IconData) obj;
            if (expanded) {
                setIcon(idata.getExpandedIcon());
            } else {
                setIcon(idata.getIcon());
            }
        } else {
            setIcon(null);
        }

        setFont(tree.getFont());
        setForeground(sel ? m_textSelectionColor
                : m_textNonSelectionColor);
        setBackground(sel ? m_bkSelectionColor
                : m_bkNonSelectionColor);
        m_selected = sel;
        return this;
    }

    public void paintComponent(Graphics g) {
        Color bColor = getBackground();
        Icon icon = getIcon();

        g.setColor(bColor);
        int offset = 0;
        if (icon != null && getText() != null) {
            offset = (icon.getIconWidth() + getIconTextGap());
        }
        g.fillRect(offset, 0, getWidth() - 1 - offset,
                getHeight() - 1);

        if (m_selected) {
            g.setColor(m_borderSelectionColor);
            g.drawRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1);
        }
        super.paintComponent(g);
    }
}

class IconData {

    protected Icon m_icon;
    protected Icon m_expandedIcon;
    protected Object m_data;

    public IconData(Icon icon, Object data) {
        m_icon = icon;
        m_expandedIcon = null;
        m_data = data;
    }

    public IconData(Icon icon, Icon expandedIcon, Object data) {
        m_icon = icon;
        m_expandedIcon = expandedIcon;
        m_data = data;
    }

    public Icon getIcon() {
        return m_icon;
    }

    public Icon getExpandedIcon() {
        return m_expandedIcon != null ? m_expandedIcon : m_icon;
    }

    public Object getObject() {
        return m_data;
    }

    public String toString() {
        return m_data.toString();
    }
}

class FileNode {

    protected File m_file;

    public FileNode(File file) {
        m_file = file;
    }

    public File getFile() {
        return m_file;
    }

    public String toString() {
        return m_file.getName().length() > 0 ? m_file.getName()
                : m_file.getPath();
    }

    public boolean expand(DefaultMutableTreeNode parent) {
        DefaultMutableTreeNode flag
                = (DefaultMutableTreeNode) parent.getFirstChild();
        if (flag == null) // No flag
        {
            return false;
        }
        Object obj = flag.getUserObject();
        if (!(obj instanceof Boolean)) {
            return false;      // Already expanded
        }
        parent.removeAllChildren();  // Remove Flag

        File[] files = listFiles();
        if (files == null) {
            return true;
        }

        Vector v = new Vector();

        for (int k = 0; k < files.length; k++) {
            File f = files[k];
            if (!(f.isDirectory())) {
                continue;
            }

            FileNode newNode = new FileNode(f);

            boolean isAdded = false;
            for (int i = 0; i < v.size(); i++) {
                FileNode nd = (FileNode) v.elementAt(i);
                if (newNode.compareTo(nd) < 0) {
                    v.insertElementAt(newNode, i);
                    isAdded = true;
                    break;
                }
            }
            if (!isAdded) {
                v.addElement(newNode);
            }
        }

        for (int i = 0; i < v.size(); i++) {
            FileNode nd = (FileNode) v.elementAt(i);
            IconData idata = new IconData(FileSystemDemo2.ICON_FOLDER,
                    FileSystemDemo2.ICON_EXPANDEDFOLDER, nd);
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
            parent.add(node);

            if (nd.hasSubDirs()) {
                node.add(new DefaultMutableTreeNode(
                        new Boolean(true)));
            }
        }

        return true;
    }

    public boolean hasSubDirs() {
        File[] files = listFiles();
        if (files == null) {
            return false;
        }
        for (int k = 0; k < files.length; k++) {
            if (files[k].isDirectory()) {
                return true;
            }
        }
        return false;
    }

    public int compareTo(FileNode toCompare) {
        return m_file.getName().compareToIgnoreCase(
                toCompare.m_file.getName());
    }

    protected File[] listFiles() {
        if (!m_file.isDirectory()) {
            return null;
        }
        try {
            return m_file.listFiles();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error reading directory " + m_file.getAbsolutePath(),
                    "Warning", JOptionPane.WARNING_MESSAGE);
            return null;
        }
    }
}
```
 

*How do I play animation in a Java program ?*

 Animating an Array of Images in an Application
 This is the simplest application to animate an array of images. 


```
/**
     * Created with IntelliJ IDEA.
     * User: JGuru
     * Date: 9/22/14
     * Time: 8:26 PM
     * To change this template use File | Settings | File Templates.
     */
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.IOException;
    
    public class AnimationApp extends JFrame {
    
        private String path = "Images/";
        // Initial Frame no.
        private int frameNumber = 1;
        private JLabel label = new JLabel();
        // Size of the Image displayed
        private Dimension dim;
        private Image image = null;
        // Total no of frames
        private int totalFrames = 0;
        // 32 for BMP, 22 for PNG format
        private int sleepTime = 29;
        private File file = new File(path);
        private String[] readFormat = ImageIO.getReaderFormatNames();
        private String prefix = "J"; // You should have Images in the format J0.png, J1.png, J2.png, J3.png
        private String[] name;
        private String extension = "png";
    
        public String[] getImages(String path) {
            name = new File(path).list(new FilenameFilter() {
    
                @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;
                }
            });
            totalFrames = name.length - 1;
            return name;
        }
    
        public AnimationApp() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                System.err.println("Error loading look 'n feel!!");
            }
    
            if (!file.exists()) {
                System.out.println("The specified path : " + path + " doesn't exist!!!");
                System.exit(1);
            }
    
            label.setHorizontalAlignment(SwingConstants.CENTER);
            label.setVerticalAlignment(SwingConstants.CENTER);
            getImages(path);
            add(label, BorderLayout.CENTER);
    
            image = getImage(path + name[0]);
            dim = new Dimension(image.getWidth(this)*2, image.getHeight(this)*2);
    
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    while (true) // put it in infinite loop
                    {
                        if (frameNumber == totalFrames) {
                                // We have reached the end, start from the beginning again
                                frameNumber = 0;
                            }
                            frameNumber++;
                            // totalFrames - > 100
                            // currentFrame -> (currentFrame*100)/totalFrames
    
                            String str = path + prefix + frameNumber + "." + extension;
                            image = getImage(str);
                            if (image != null) {
                                image.setAccelerationPriority(0.9f);
                                label.setIcon(new ImageIcon(image.getScaledInstance(dim.width, dim.height, Image.SCALE_DEFAULT)));
                                sleep(sleepTime);
                            }
    
                    }
                }
            }).start();
            //Frame's properties
            setTitle("Animation Demo");
            setSize(dim.width + 40, dim.height + 40);
            setLocationRelativeTo(this);
            setResizable(false);
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    
        public Image getImage(String fileName) {
            try {
                return ImageIO.read(new File(fileName));
            } catch (IOException ioe) {
            }
            return null;
        }
    
        public void print(String msg) {
            System.out.println(msg);
        }
    
        public void sleep(long ms) {   //     millis - the length of time to sleep in milliseconds.
            //nanos - 0-999999 additional nanoseconds to sleep.
            // sleep(millis, nanos)
            // This synchronizes the Audio with the Video
            try {
                Thread.sleep(ms, 700);
            } catch (InterruptedException ie) {
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new AnimationApp();
                }
            });
        }
    }
```

*s29.postimg.org/reyuo0cgj/Animation_App.jpg

Here is another example showing animation in action in a Java Applet!!!

*Animation.java*


```
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.applet.*; 
 
 
public class Animation extends JApplet implements ActionListener 
{ 
    ImageSQPanel imageSQPanel; 
    static int frameNumber = -1; 
    int delay; 
    Thread animatorThread; 
    static boolean frozen = false; 
    Timer timer; 
    MediaTracker tracker;
    int width = 700;
    int height = 447;


    //Invoked only when this is run as an applet.
    public void init()
    {
        //Get the images.
        Image[] images = new Image[60];

        tracker = new MediaTracker(this);

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

            images[i-1] = getImage(getCodeBase(), "SM"+i+".png");
            try
            {

               tracker.addImage(images[i-1], 1);
               tracker.waitForID(1);

            } catch (Exception e) {}
        }
        buildUI(getContentPane(), images);
        startAnimation();
    }

    //Note: Container must use BorderLayout, which is the
    //default layout manager for content panes.
    void buildUI(Container container, Image[] dukes)
    {
        int fps = 10;

        //How many milliseconds between frames?
        delay = (fps > 0) ? (1850 / fps) : 100; // 1000 / fps

        //Set up a timer that calls this object's action handler
        timer = new Timer(delay, this);
        timer.setInitialDelay(0);
        timer.setCoalesce(true);

        imageSQPanel = new ImageSQPanel(dukes);
        container.add(imageSQPanel, BorderLayout.CENTER);

        imageSQPanel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (frozen)
                {
                    frozen = false;
                    startAnimation();
                }
                else
                {
                    frozen = true;
                    stopAnimation();
                }
            }
       });
    }

    public void start()
    {
        startAnimation();
    }

    public void stop()
    {
        stopAnimation();
    }

    public synchronized void startAnimation()
    {
        if (frozen)
        {
            //Do nothing.  The user has requested that we
            //stop changing the image.
        }
        else
        {
            //Start animating!
            if (!timer.isRunning())
            {
                timer.start();
            }
        }
    }

    public synchronized void stopAnimation()
    {
        //Stop the animating thread.
        if (timer.isRunning())
        {
            timer.stop();
        }
    }

    public void actionPerformed(ActionEvent e)
    {
        //Advance the animation frame.
        frameNumber++;

        //Display it.
        imageSQPanel.repaint();
    }

    class ImageSQPanel extends JPanel
    {
        Image dukesWave[];

        public ImageSQPanel(Image[] dukesWave)
        {
            this.dukesWave = dukesWave;
        }

        //Draw the current frame of animation.
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g); //paint background

            if ((tracker.statusAll(false) & MediaTracker.ERRORED) != 0)
            {
              g.setColor(Color.red);
              g.fillRect(0, 0, getSize().width, getSize().height);
              return;
            }

            if (tracker.statusID(1, false) == MediaTracker.COMPLETE)
            {
               //Paint the frame into the image.
              try
              {
                  g.drawImage(dukesWave[Simran.frameNumber%60], 0, 0, width, height, this);
              } catch (ArrayIndexOutOfBoundsException e) {
                //On rare occasions, this method can be called
                //when frameNumber is still -1.  Do nothing.
                return; }
            } // close if
        }
    }

}
```

*s2.postimg.org/ussnx8aid/Animation.jpg

 Here is the HTML file for the Applet.

*example1.html*

```
<html>
<applet code ="Animation.class" width = 700 height = 447> 
</applet> 
</html>
```

 The program needs 60 Images of SM0.png SM1.png .... SM59.png  .

 You put a VCD into your DVD Drive & select a song (dance sequence), extract the Images , pick every 25th Image & copy it to a separate directory.
 Rename them as SM0.png, SM1.png etc., We need 60 Images for a good Applet animation. 

  Here is the procedure to extract the Images from a VCD using VirtualDubMod (*sourceforge.net/projects/virtualdubmod/)
  Select the song from the VCD. Wait for it load completely. From the menu select File -> Save Image sequence..., A dialog pops out. Select the output format as "PNG".
  Enter the file prefix name as  SM 
  Select a directory to hold these Images. Now click on the OK button. It will take a few minutes time. So wait until the Images are extracted!!!

  You can also extract the audio (WAV format) using VirtualDub. Play the animation with audio & Image. Synchronize both to create an excellent animation!!!!
  I will leave that to you!!! 


*Java Media Framework *(JMF) can be used to play MP3 & MPEG video files in Java.
  Download JMF at *kaz.dl.sourceforge.net/project/fob...4JMF-0.4.1/fobs4jmf-0.4.1-win32-installer.exe

*Java Advanced Imaging *(JAI) can be used to apply various Image filters & algorithms
  JAI is available at 
   *download.java.net/media/jai-imageio/builds/release/1.1/jai_imageio-1_1-lib-windows-i586-jdk.exe  (Windows)
   *download.java.net/media/jai-imageio/builds/release/1.1/jai_imageio-1_1-lib-linux-i586-jdk.bin  (Linux)

*JavaHelp* -  to view help files in Java
  *javahelp.dev.java.net/

*JavaMail* - to send & view emails


*Java3D* - To view 3D animations & effects 
  *java3d.dev.java.net/

*Java Application Viewing libraries*:


 1) iText ( *www.lowagie.com/iText/ ) -> Read & Write PDF using Java

 2) JExcelAPI ( *jexcelapi.sourceforge.net/ ) -> Read & write Excel files using Java

 3) Jakarta POI ( *jakarta.apache.org/poi/ ) -> manipulate Microsoft's OLE2 format

 4) More Open Source PDF libraries ( *java-source.net/open-source/pdf-libraries )

 5) Javio (*www.javio.com/)

 6) JIDE's Swing Component Suite (*www.jidesoft.com/products/download.htm)

 7) JProductivity (*www.jproductivity.com/products/components/components.htm)

 8) Wingz (*www.zvalley.com/wingz-demos.htm)

 9) iLog (*www.ilog.com/products/jviews/demos/index.cfm)

 10) EPhox (*www.ephox.com/products/)

 11) IceSoft (*www.icesoft.com/products/index.html)

 12) JFreeChart (*www.jfree.org/jfreechart)

 13) JGraph (*www.jgraph.com/)

 14) Monarch Charts ( *www.singleton-labs.com/)

 15) yWorks (*www.yworks.com/products)

 16) JCalendar (*www.toedter.com/en/jcalendar)

 17) OSwing (*oswing.sourceforge.net/)

 18) Advanced Table Component (*www.advancedtable.com/ext/)

 19) JGUI (*reader.imagero.com/jgui/)

 20) Java Print Dialog Framework (*www.softframeworks.com/)

 21) VLDocking Framework (*www.vlsolutions.com/en/products/docking/)

 22) JFDraw (*www.jfimagine.com/)

 23) GEF (*gef.tigris.org/)

 24) Gandalf Wizard Framework (*sourceforge.net/projects/gandalf/)

 25) JImageDialog (*asprise.com/product/jid/index.php)

 26) JForm (*www.coderight.nl/)

 27) JClass (*www.quest.com/jclass/)

 28) UIHierarchy (*sourceforge.net/projects/uihierarchy/)



*Layout Managers*:
  Use the free Layout managers to write better code in Java.


 1) TableLayout ( *tablelayout.dev.java.net/)

 2) MiGLayout (*www.miglayout.com/)

 3) RiverLayout (*today.java.net/pub/n/RiverLayout)

 4) FormLayout (*forms.dev.java.net/)

 5) Packer Layout (*packer.dev.java.net/)

 6) Page Layout (*pagelayout.sourceforge.net/)

 7) Explicit Layout (*www.zookitec.com/explicitlayout.html)

 8) FlexiLayout *www.bolthole.com/java/flexilayout.html)

 9) HiGLayout *www.autel.cz/dmi/tutorial.html)

 10) XmFormLayout (*www.softbear.com/java/xmformlm/xmformlm.htm)

 11) ExpressionLayout (*expressionlayout.dev.java.net/)

 12) BiX ( *bix.sourceforge.net/)

 13) EasyLayout ( *sourceforge.net/projects/easylayout/)

 14) Transparent Layout ( *transparentlayout.dev.java.net/)



*Java Look n Feel's* :


 1) Kunststoff ( *www.incors.org/ )

 2) Liquid    ( *liquidlnf.sourceforge.net/ )

 3) Metouia ( *mlf.sourceforge.net/ )

 4) Napkin ( *napkinlaf.sourceforge.net/ )

 5) Skin ( *www.l2fprod.com/ )

 6) NextStep ( *hp.vector.co.jp/authors/VA008030/swing/ )

 7) Squareness ( *squareness.sourceforge.net/ )

 8) Tiny ( *www.muntjak.de/hans/java/tinylaf/index.html )

 9) Tonic ( *www.digitprop.com/p.php?page=toniclf&lang=eng )

10) Goodies Looks ( *www.jgoodies.com/ )


*Swing Depot: Component Suites* :

   *www.javadesktop.org/rollups/components/index.html

   *weblogs.java.net/blog/hansmuller/archive/2004/10/and_then_there.html


*Open source projects in Java*


  *www.ibm.com/developerworks/java/find/projects/
  *java-source.net/
  *sourceforge.net
  *code.google.com


*Top 10 Java Applications*:

   *java.dzone.com/tips/ten-amazing-java-applications


*Cool Java Applets*

  Some very cool Java Applets that I stumbled upon the Web.

  *www.falstad.com/mathphysics.html 

  *www.anfyteam.com/ajdownl.html

  *www.dseffects.com/f_applets.html

  *www.javaonthebrain.com/brain.html  

  *www.astro.wisc.edu/~dolan/java/

  *jcrystal.com/steffenweber/java.html


*Java Q & A*:


  Q) Java is slow, how can I speed it up?

  Ans. Java is slow because it's a interpreted language. Using more RAM will speed up Java applications a bit (minimum 4GB, for best performance 6GB).
       Another solution is to use a JIT Compiler like Excelsior JET ( www.excelsior-usa.com/jet.html). A JIT compiler translates the bytecode
       to native code. That makes the Java application run as fast as a C/C++ application.Remember if you use a JIT compiler then the program
       is tied to a particular platform!! Also having a GPU like NVidia speeds up java2D by 25%!! You must use a 64-bit OS to utilize the entire RAM.
       ie., 64-bit Windows or 64-bit Linux

       Here are some simple cmd-line tricks you can use to load Java applications faster!!! (Swing Secrets Revealed : *weblogs.java.net/blog/alexfromsun/archive/2006/04/swing_team_reve_1.html)

       XVerify:none - Don't verify the integrity of the btycode!!

       swing.runtwiceasfast=true - Make Swing run twice as fast!!!

       java2d.speedofpainting=UNIMAGINABLE - Makes Java2D run at an unbelievable speed!!

       Here is how you can use it.

*java -Xverify:none -Dswing.runtwiceasfast=true -Djava2d.speedofpainting=UNIMAGINABLE ClassName*

*java -Xverify:none -Dswing.runtwiceasfast=true -Djava2d.speedofpainting=UNIMAGINABLE -jar SwingSet2.jar*

       You can create a batch file (Windows), shell script (Linux, Solaris, Mas OS) & click to execute it, instead of typing the whole thing again & again!!!

       Here is how you can speed up NetBeans IDE loading process by 25%!!!

       Open the cmd-line , cd to C:\Program Files\NetBeans 7.4\etc (Windows 32-bit) or C:\Program Files (x86)\NetBeans 7.4\etc (Windows 64-bit)


```
cd C:\Program Files\NetBeans 7.4\etc
```
 

```
copy netbeans.conf netbeans.conf_back
```

       The NetBeans Configuration file is stored in the 'etc' folder (netbeans.conf)

       Here is modified version of the configuration file

*netbeans.conf*


```
# Default locations of userdir and cachedir:
# (*wiki.netbeans.org/FaqWhatIsUserdir)
#
# On Windows ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "<AppData>\NetBeans" where <AppData> is user's
# value of "AppData" key in Windows Registry under
# "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
# and ${DEFAULT_CACHEDIR_ROOT} will be replaced by the launcher
# with "<Local AppData>\NetBeans\Cache" where <Local AppData> is user's
# value of "Local AppData" key in Windows Registry under
# "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
#
# On Mac ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "~/Library/Application Support/NetBeans" and
# ${DEFAULT_CACHEDIR_ROOT} with "~/Library/Caches/NetBeans"
#
# On other systems ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "~/.netbeans" and ${DEFAULT_CACHEDIR_ROOT} with "~/.cache/netbeans"
#
# You can also use ${HOME} variable which will be replaced with
# user.home JVM system property value. This variable is valid only in
# netbeans_default_userdir and netbeans_default_cachedir properties.
#
# NOTE: If you specify a non-default userdir path on command line
# (--userdir option) and don't specify a cachedir path (--cachedir option),
# cachedir will be in "<userdir>/var/cache".
#
# Cachedir must be different from userdir. The same cachedir and userdir
# would cause problems.
#
netbeans_default_userdir="${DEFAULT_USERDIR_ROOT}/7.4beta"
netbeans_default_cachedir="${DEFAULT_CACHEDIR_ROOT}/7.4beta"

# Options used by NetBeans launcher by default:
# (can be overridden by explicit command line switches)
#
# Note that default -Xmx and -XX:MaxPermSize are selected for you automatically.
# You can find these values in var/log/messages.log file in your userdir.
# The automatically selected value can be overridden by specifying -J-Xmx or
# -J-XX:MaxPermSize= here or on the command line.
#
# If you specify the heap size explicitly, you may also want to enable
# Concurrent Mark & Sweep garbage collector.
# (see *wiki.netbeans.org/FaqGCPauses)
#
netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-Dnetbeans.logger.console=true -J-ea -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Dnetbeans.extbrowser.manual_chrome_plugin_install=yes -J-Dswing.runtwiceasfast=true -J-Djava2d.speedofpainting=UNIMAGINABLE"

# Default location of JDK:
# (set by installer or commented out if launcher should decide)
#
# It can be overridden on command line by using --jdkhome <dir>
# Be careful when changing jdkhome.
# There are two NetBeans launchers for Windows (32-bit and 64-bit) and
# installer points to one of those in the NetBeans application shortcut
# based on the Java version selected at installation time.
#
netbeans_jdkhome="C:\Program Files\Java\jdk1.7.0_25"

# Additional module clusters:
# using ${path.separator} (';' on Windows or ':' on Unix):
#
#netbeans_extraclusters="/absolute/path/to/cluster1:/absolute/path/to/cluster2"
```


  Save this file  as 'netbeans.conf' in the 'etc' (C:\Program Files\NetBeans 7.4\etc (Windows 32-bit) or C:\Program Files (x86)\NetBeans 7.4\etc  (Windows 64-bit) ) folder under NetBeans installation directory.
  Now start NetBeans IDE, you will see faster IDE startup!!!

  Also checkout IBM's SWT (Standand Widget Toolkit): SWT is a set of classes & libraries written in C. SWT is available for Windows, Linux, Solaris, Mac OS.
  Since SWT library is 32-bit. It only works with 32-bit JDK!!

   *www.eclipse.org/swt/

   SWT Code Examples:
  ---------------------

   *www.eclipse.org/swt/snippets/

   To compile & run SWT programs in the chosen OS you must download the swt.jar file for the particular OS. 
   If you use a IDE like NetBeans , JDeveloper, or Eclipse create a new library called 'SWT' & include it in the project. SWT is 10 times faster than Java Swing, since it's written 
   entirely in C language.


  Q) My program is throwing a OutofMemory error?

  Ans. The reason your Java program is throwing a OutOfMemory error, because the JVM can't allocate enough memory requested by the program.
       The solution is to use the -Xms & -XmX cmd-line argument.

*java -Xms128m -Xmx256m ClassName*

       This tells the JVM to allocate 128 MB as initially & a maximum of 256 MB (memory is allocated from the Heap area)

       Also you should install a 64-bit JDK if you use a 64-bit OS. A 64-bit OS can allocate more heap. A 64-bit Java JVM can allocate 5.5 GB of memory.

  Q) I have finished my College, what skills are needed to fetch me a programmer job?

  Ans. You need to be a Graduate with 60% (Some companies ask for 70%)(Preferably a BE/ Msc/ MS IT/ MCA). Should be good in problem solving (logical reasoning).
  Also familiar with C/C++, Java, Oracle.Must have done a good project in Java. Know how to program in Java or any other language . Good Communication skills are also essential.

  Q) Does Java certification fetch me a job?

  Ans.  Certification in Java alone will not fetch you a job!! You should have a very good knowledge of Java language (Pass the Java Knowledge Test in the Company)
        You should have done a good project in Java. Also prepare a Project book. A project book contains the synopsis of the project. The System Development Cycle,
        Dataflow diagrams, screenshots of the project (modules), detailed explanation of each & very feature. Excellent understanding of Data-Structures & Algorithms
        in Java. Most of the guys don't get a job because they have no programming skills , poor Java knowledge , poor communication skills. 

        First develop good programming skills, communication skills, etc.,
        I know Java, C/C++ is not enough!! You should be able to apply your Java knowledge & logic to develop
        a software application. We can't put you straightaway in a 100 crore Banking project, since you don't know ABC of programming!!!
        So develop good programming skill in Java. Learn how to program by studying these books & write more programs!!

        I recommend these books for study.

      1) Core Java - Vol -I & II by Horstmann C S

      2) Beginning Java Objects (Wrox)/ Object-Oriented Programming in Java by Balagurusamy

      3) Java Tutorial 5th Edition

      4) Graphic Java 2 ,Volume 2 Swing: Mastering the JFC by David M Geary

      5) Data Structures & Algorithms in Java by Robert Lafore (Techmedia)

      6) The Java Developers Almanac 1.4, Volume I & II by Patrick Chan

      7) Java Swing 5th Edition by Eckstein (Oreilly)

      8) Thinking in Java 

      9) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty

      10) Oracle Database JDBC Developer's Guide & Reference

      11) Beginning Java Databases / Java Database Programming Bible by John O' Donahue 

      12) Professional Java Programming (Wrox)

      13) Beginning Java Networking (Wrox)/ An Itroduction to Network Programming with Java : Java 7 Compatible by Jan Graba

      14) JSP 2.0 : The Complete Reference by Phil Hanna (Tata McGraw Hill)

      15) Struts : The Complete Reference (Tata McGraw Hill)

      16) Mastering HTML 5 (Sybex/ BPB)

      17) Professional Java Networking (Wrox)

      18) Oracle 12c: The Complete Reference (Tata McGraw Hill)

      19) Java Threads (Oreilly)

      20) Java How To Program by H M Deitel & P J Deitel 

      21) Software Engineering in Java 

      23) Desktop Java Live (Discusses various Layout Managers , GUI Builders, Swing Threading, Data Binding , Validation, Packaging & Deployment )

      24) Java Servlet Programming by Jason Hunter, William Crawford (Oreilly)

      25) The Java FAQ (The Java Series) by Jonni Kanerva - Useful to answer Interview questions

     Study these books , apply Java & create a meaningful project. Create a project book with screenshots of the software application.
     You must remember that writing a good software application takes months or years (12 months or more).
     So work hard & create a software application after studying these books.
     Most of the guys haven't written program bigger than 300 lines!! If you sincerly don't understand programming.
     Then start from the basics by studying these books & download & study a Open Source project.
     First understand what's programming, how to apply your Java or C++ knowledge to solve real-world problem (project)
     Remember it takes months to become a good programmer.

  Q) How can I write various Charts in Java?

  Here is a BarChart demo


```
//BarChartDemo.java
  import java.awt.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import javax.swing.*;
  
  /**
   * A simple bar chart demo
   *
   * @author JGuru
   *
   */
  public class BarChartDemo extends JPanel {
  
      private static final int VERTICAL = 0;
      private static final int HORIZONTAL = 1;
      private static final int SOLID = 0;
      private static final int STRIPED = 1;
      private int orientation = HORIZONTAL;
      private final String title = "Fruits Chart";
      private final Font font;
      private final FontMetrics metrics;
      private final int columns = 6;
      private final int values[] = {10, 20, 5, 30, 40, 17};
      private final Color colors[] = {Color.red, Color.orange, Color.yellow, Color.pink, Color.green, Color.magenta};
      private final String labels[] = {"Apple", "Orange", "Lemon", "Peach", "Pear", "Plum"};
      private final int styles[] = {SOLID, STRIPED, SOLID, STRIPED, SOLID, STRIPED};
      private final int scale = 10;
      private final int maxLabelWidth = 40;
      private final int barSpacing = 20;
      private final int maxValue = 0;
      private JCheckBox horizCheckBox;
      private static JPanel bottom;
  
      public BarChartDemo() {
          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
          }
          horizCheckBox = new JCheckBox("Horizontal", true);
          bottom = new JPanel(new FlowLayout(FlowLayout.CENTER));
          font = new Font("Monospaced", Font.BOLD, 12);
          metrics = getFontMetrics(font);
          Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
          bottom.add(new JLabel("Orientation : "));
          bottom.add(horizCheckBox);
          setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height / 2));
          horizCheckBox.addActionListener(new ActionListener() {
  
              @Override
              public void actionPerformed(ActionEvent e) {
                  if (horizCheckBox.isSelected()) {
                      orientation = HORIZONTAL;
                  } else {
                      orientation = VERTICAL;
                  }
                  repaint();
              }
          });
      }
  
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g;
          // Set the rendering hints
          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);
          g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          // draw the title centered at the bottom of the bar graph
          g2d.setColor(Color.black);
          g2d.setFont(font);
  
          g2d.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
  
          int titleWidth = metrics.stringWidth(title);
          int cx = Math.max((getSize().width - titleWidth) / 2, 0);
          int cy = getSize().height - metrics.getDescent();
          g2d.drawString(title, cx, cy - 10);
  
          // draw the bars and their titles
          if (orientation == HORIZONTAL) {
              paintHorizontal(g2d);
          } else {  // VERTICAL
              paintVertical(g2d);
          }
      }
  
      private void paintHorizontal(Graphics2D g) {
          // x and y coordinates to draw/write to
          int cx, cy;
          int barHeight = metrics.getHeight();
  
          for (int i = 0; i < columns; i++) {
  
              // set the X coordinate for this bar and label and center it
              int widthOfItems = maxLabelWidth + 3 + (maxValue * scale) + 5
                      + metrics.stringWidth(Integer.toString(maxValue));
              cx = Math.max((getSize().width - widthOfItems) / 4, 0);
  
              // set the Y coordinate for this bar and label
              cy = (getSize().height - metrics.getDescent() - metrics.getHeight()
                      - barSpacing
                      - ((columns - i - 1) * (barSpacing + barHeight * 3))) / 2 + 150;
  
              // draw the label
              g.setColor(Color.black);
              g.drawString(labels[i], cx, cy);
              cx += maxLabelWidth + 3;
  
              // draw the shadow
              g.fillRect(cx + 4, cy - barHeight + 4,
                      (values[i] * scale), barHeight);
  
              // draw the bar
              g.setColor(colors[i]);
              if (styles[i] == STRIPED) {
                  for (int k = 0; k <= values[i] * scale; k += 2) {
                      g.drawLine(cx + k, cy - barHeight, cx + k, cy);
                  }
              } else {      // SOLID
                  g.fillRect(cx, cy - barHeight,
                          (values[i] * scale) + 1, barHeight + 1);
              }
              cx += (values[i] * scale) + 4;
  
              // draw the value at the end of the bar
              g.setColor(g.getColor().darker());
              g.drawString(Integer.toString(values[i]), cx, cy);
          }
      }
  
      private void paintVertical(Graphics2D g) {
          int barWidth = maxLabelWidth;
  
          for (int i = 0; i < columns; i++) {
  
              // X coordinate for this label and bar (centered)
              int widthOfItems = (barWidth + barSpacing) * columns - barSpacing;
              int cx = Math.max((getSize().width - widthOfItems) / 2, 0);
              cx += (maxLabelWidth + barSpacing) * i;
  
              // Y coordinate for this label and bar
              int cy = getSize().height - metrics.getHeight()
                      - metrics.getDescent() - 4;
  
              // draw the label
              g.setColor(Color.black);
              g.drawString(labels[i], cx, cy);
              cy -= metrics.getHeight() - 3;
  
              // draw the shadow
              g.fillRect(cx + 4, cy - (values[i] * scale) - 4,
                      barWidth, (values[i] * scale));
  
              // draw the bar
              g.setColor(colors[i]);
              if (styles[i] == STRIPED) {
                  for (int k = 0; k <= values[i] * scale; k += 2) {
                      g.drawLine(cx, cy - k,
                              cx + barWidth, cy - k);
                  }
              } else {
                  g.fillRect(cx, cy - (values[i] * scale),
                          barWidth + 1, (values[i] * scale) + 1);
              }
              cy -= (values[i] * scale) + 5;
  
              // draw the value on top of the bar
              g.setColor(g.getColor().darker());
              g.drawString(Integer.toString(values[i]), cx, cy);
          }
      }
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
  
              @Override
              public void run() {
                  JFrame f = new JFrame("BarChartDemo");
                  f.add(new BarChartDemo(), BorderLayout.CENTER);
                  f.add(bottom, BorderLayout.SOUTH);
                  f.pack();
                  f.setLocationRelativeTo(null);
                  f.setVisible(true);
                  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              }
          });
      }
  }
```

  *s12.postimg.org/7z5w45xkp/Bar_Chart_Demo.jpg

  Here is a PieChart demo


```
//PieChartDemo.java
  //Drawing a Pie Chart
  //This example implements a method for drawing a pie chart.
  import java.awt.*;
  import javax.swing.*;
  
  // Class to hold a value for a slice
  class PieChart {
  
      private double value;
      private Color color;
      private Font textFont = new Font("Serif", Font.BOLD, 16);
      private Color textColor = Color.black;
      private int originX, originY;
      private int radius;
      private double d2r = Math.PI / 180.0; // degrees to radians.
  
      public PieChart(double value, Color color) {
          this.value = value;
          this.color = color;
      }
  
      // slices is an array of values that represent the size of each slice.
      public void drawPie(Graphics2D g, Rectangle area, PieChart[] slices, String[] labels) {
          originX = area.width / 2;
          originY = area.height / 2;
          int diameter = (originX < originY ? area.width - 40
                  : area.height - 40);
          radius = (diameter / 2) + 1;
          // Get total value of all slices
          double total = 0.0D;
          for (int i = 0; i < slices.length; i++) {
              total += slices[i].value;
          }
  
          // Draw each pie slice
          double curValue = 0.0D;
          int startAngle = 0;
          for (int i = 0; i < slices.length; i++) {
              // Compute the start and stop angles
              startAngle = (int) (curValue * 360 / total);
              int arcAngle = (int) (slices[i].value * 360 / total);
  
              // Ensure that rounding errors do not leave a gap between the first and last slice
              if (i == slices.length - 1) {
                  arcAngle = 360 - startAngle;
              }
  
              // Set the color and draw a filled arc
              g.setColor(slices[i].color);
              g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
  
              curValue += slices[i].value;
              // Draw the Labels
              drawLabel(g, labels[i] + " - " + (int) slices[i].value + "%", startAngle + (arcAngle / 2));
          }
      }
  
      //Draw the labels
      public void drawLabel(Graphics g, String text, double angle) {
          g.setFont(textFont);
          g.setColor(textColor);
          double radians = angle * d2r;
          int x = (int) ((radius + 5) * Math.cos(radians));
          int y = (int) ((radius + 5) * Math.sin(radians));
          if (x < 0) {
              x -= SwingUtilities.computeStringWidth(g.getFontMetrics(), text);
          }
          if (y < 0) {
              y -= g.getFontMetrics().getHeight();
          }
          g.drawString(text, x + originX, originY - y);
      }
  
  }
  
  public class PieChartDemo extends JPanel {
  
      private PieChart[] slices = new PieChart[4];
      private Rectangle area;
      private int width, height;
      private int percent[] = {25, 33, 20, 15};
      private String[] language = {"C++", "Java", "C#", "Visual Basic"};
      private Color color[] = {Color.red, Color.green, Color.pink, Color.blue};
  
      PieChartDemo() {
          // Set the size of the Component
          Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
          setPreferredSize(new Dimension(scrDim.height / 2 + 250, scrDim.height / 2 + 150));
      }
  
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          width = getWidth();
          height = getHeight();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
          g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
          g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
          g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          g2.setStroke(new BasicStroke(1.5f));
  
          area = new Rectangle(20, 20, width - 40, height - 40);
          for (int i = 0; i < slices.length; i++) {
              slices[i] = new PieChart(percent[i], color[i]);
          }
          slices[0].drawPie(g2, area, slices, language);
      }
  
      public static void main(String[] arg) {
          SwingUtilities.invokeLater(new Runnable() {
  
              @Override
              public void run() {
                  JFrame f = new JFrame("PieChart Demo");
                  f.add(new PieChartDemo());
                  f.pack();
                  f.setLocationRelativeTo(null);
                  f.setVisible(true);
                  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              }
          });
      }
  }
```

   *s1.postimg.org/gucn3erkb/Pie_Chart_Demo.jpg
    JFreeChart (*www.jfree.org/jfreechart) is a free utility to draw various Charts like BarChart , PieChart, AreaCharts, Gantt Chart, Line Chart, Financial Charts, Statistical Charts,

  Time Series Charts , etc., 

  Remember to run these demos you need to include jfreechart-1.0.15.jar & jcommon-1.0.18.jar in your CLASSPATH!!! Otherwise the program won't compile!!!

   Here is how:

    To Compile

    Windows

    javac -cp .;"path-to/jfreechart-1.0.15.jar;path-to/jcommon-1.0.18.jar" BarChartDemo1.java

    Linux

    javac -cp .;"path-to/jfreechart-1.0.15.jarath-to/jcommon-1.0.18.jar" BarChartDemo1.java

    To Run

    Windows

    java -cp .;"path-to/jfreechart-1.0.15.jar;path-to/jcommon-1.0.18.jar" BarChartDemo1


    Linux

    java -cp .;"path-to/jfreechart-1.0.15.jarath-to/jcommon-1.0.18.jar" BarChartDemo1

    Alternatively you can copy the JAR file jfreechart-1.0.15.jar & jcommon-1.0.18.jar to the extension folder.

    Windows  (32-bit & 64-bit JDK )

32-bit JDK in Windows 32-bit, or 64-bit JDK in Windows 64-bit


*C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext*

32-bit JDK in Windows 64-bit

*C:\Program Files (x86)\Java\jdk1.7.0_25\jre\lib\ext*

    There is also a JRE folder under the Java folder (C:\Program Files\Java\jre7) also copy the JAR files to the ext folder (C:\Program Files\Java\jre7\lib\ext) 
    For JDK 7 it's JRE7, for JDK 8 it's JRE8 and so on.

    Linux

*/usr/java/jdk1.7.0_25/jre/lib/ext* 

    Some Linux distros like Debian, Ubuntu, Knoppix, Suse install Java JDK in some alternate location.
    You need to search it & copy the JAR files to the appropriate directory.

    Since You have copied the JAR file containing the packages needed for the demos to the ext folder.

    You can compile & run the demos like a normal Java program!!!

    When JVM loads it searches for the necessary class files (packages) in the "lib" & "ext" directories.If it finds the class files there, then the program
    will compile & run without any problem!!

    Alternatively those who use IDE like NetBeans , Eclipse, IDEA can create a library called 'JFreeChart'
      & include the library to compile & run the project

   Procedure: In NetBeans IDE from the menu Tools - > Libraries -> Click on button "New library..." on the left side, enter the library name as 'JFreeChart' & click on the 
  'Add JAR/Folder...' Create a 'lib' directory under the project folder & place the JAR files jfreechart-1.0.15.jar, jcommon-1.0.18.jar there. 

  Here is a demo that shows a BarChart!!

    BarChartDemo1.java


```
import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GradientPaint;
    import java.awt.Toolkit;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.StandardChartTheme;
    import org.jfree.chart.axis.CategoryAxis;
    import org.jfree.chart.axis.CategoryLabelPositions;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.renderer.category.BarRenderer;
    import org.jfree.data.category.CategoryDataset;
    import org.jfree.data.category.DefaultCategoryDataset;
    import org.jfree.ui.ApplicationFrame;
    import org.jfree.ui.RefineryUtilities;
    
    /**
     * A simple demonstration application showing how to create a bar chart.
     */
    public class BarChartDemo1 extends ApplicationFrame {
    
        private static final long serialVersionUID = 1L;
    
        {
            // set a theme using the new shadow generator feature available in
            // 1.0.14 - for backwards compatibility it is not enabled by default
            ChartFactory.setChartTheme(new StandardChartTheme("JFree/Shadow",
                    true));
        }
    
        /**
         * Creates a new demo instance.
         *
         *  [MENTION=9956]PARAM[/MENTION] title the frame title.
         */
        public BarChartDemo1(String title) {
            super(title);
            CategoryDataset dataset = createDataset();
            JFreeChart chart = createChart(dataset);
            ChartPanel chartPanel = new ChartPanel(chart);
            chartPanel.setFillZoomRectangle(true);
            chartPanel.setMouseWheelEnabled(true);
            Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
    
            chartPanel.setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height / 2));
            setContentPane(chartPanel);
        }
    
        /**
         * Returns a sample dataset.
         *
         * @return The dataset.
         */
        private static CategoryDataset createDataset() {
    
            // row keys...
            String series1 = "First";
            String series2 = "Second";
            String series3 = "Third";
    
            // column keys...
            String category1 = "Category 1";
            String category2 = "Category 2";
            String category3 = "Category 3";
            String category4 = "Category 4";
            String category5 = "Category 5";
    
            // create the dataset...
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    
            dataset.addValue(1.0, series1, category1);
            dataset.addValue(4.0, series1, category2);
            dataset.addValue(3.0, series1, category3);
            dataset.addValue(5.0, series1, category4);
            dataset.addValue(5.0, series1, category5);
    
            dataset.addValue(5.0, series2, category1);
            dataset.addValue(7.0, series2, category2);
            dataset.addValue(6.0, series2, category3);
            dataset.addValue(8.0, series2, category4);
            dataset.addValue(4.0, series2, category5);
    
            dataset.addValue(4.0, series3, category1);
            dataset.addValue(3.0, series3, category2);
            dataset.addValue(2.0, series3, category3);
            dataset.addValue(3.0, series3, category4);
            dataset.addValue(6.0, series3, category5);
    
            return dataset;
    
        }
    
        /**
         * Creates a sample chart.
         *
         *  [MENTION=9956]PARAM[/MENTION] dataset the dataset.
         *
         * @return The chart.
         */
        private static JFreeChart createChart(CategoryDataset dataset) {
    
            // create the chart...
            JFreeChart chart = ChartFactory.createBarChart(
                    "Bar Chart Demo 1", // chart title
                    "Category", // domain axis label
                    "Value", // range axis label
                    dataset, // data
                    PlotOrientation.VERTICAL, // orientation
                    true, // include legend
                    true, // tooltips?
                    false // URLs?
                    );
    
            // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
            // set the background color for the chart...
            chart.setBackgroundPaint(Color.white);
    
            // get a reference to the plot for further customisation...
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
    
            // set the range axis to display integers only...
            NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
            rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    
            // disable bar outlines...
            BarRenderer renderer = (BarRenderer) plot.getRenderer();
            renderer.setDrawBarOutline(false);
    
            // set up gradient paints for series...
            GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue,
                    0.0f, 0.0f, new Color(0, 0, 64));
            GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green,
                    0.0f, 0.0f, new Color(0, 64, 0));
            GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red,
                    0.0f, 0.0f, new Color(64, 0, 0));
            renderer.setSeriesPaint(0, gp0);
            renderer.setSeriesPaint(1, gp1);
            renderer.setSeriesPaint(2, gp2);
    
            CategoryAxis domainAxis = plot.getDomainAxis();
            domainAxis.setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions(
                    Math.PI / 6.0));
            // OPTIONAL CUSTOMISATION COMPLETED.
    
            return chart;
    
        }
    
        /**
         * Starting point for the demonstration application.
         *
         *  [MENTION=9956]PARAM[/MENTION] args ignored.
         */
        public static void main(String[] args) {
            BarChartDemo1 demo = new BarChartDemo1("BarChart Demo1");
            demo.pack();
            RefineryUtilities.centerFrameOnScreen(demo);
            demo.setVisible(true);
        }
    }
```

    *s9.postimg.org/khv4nds6j/Bar_Chart_Demo1.jpg

   Here is a Cylinder Chart demo
     CylinderChartDemo2.java


```
import java.awt.*;
     import javax.swing.JPanel;
     import org.jfree.chart.ChartFactory;
     import org.jfree.chart.ChartPanel;
     import org.jfree.chart.ChartUtilities;
     import org.jfree.chart.JFreeChart;
     import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
     import org.jfree.chart.plot.CategoryPlot;
     import org.jfree.chart.plot.PlotOrientation;
     import org.jfree.data.category.CategoryDataset;
     import org.jfree.data.category.DefaultCategoryDataset;
     import org.jfree.ui.ApplicationFrame;
     import org.jfree.ui.GradientPaintTransformType;
     import org.jfree.ui.RefineryUtilities;
     import org.jfree.ui.StandardGradientPaintTransformer;
     
     public class CylinderChartDemo2 extends ApplicationFrame {
     
         public CylinderChartDemo2(String paramString) {
             super(paramString);
             ChartPanel localChartPanel = (ChartPanel) createDemoPanel();
             Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
             localChartPanel.setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height / 2));
             setContentPane(localChartPanel);
         }
     
         private static CategoryDataset createDataset() {
             DefaultCategoryDataset localDefaultCategoryDataset = new DefaultCategoryDataset();
             localDefaultCategoryDataset.addValue(4.0D, "S1", "Monday");
             localDefaultCategoryDataset.addValue(5.0D, "S1", "Tuesday");
             localDefaultCategoryDataset.addValue(-7.0D, "S1", "Wednesday");
             localDefaultCategoryDataset.addValue(6.0D, "S1", "Thursday");
             localDefaultCategoryDataset.addValue(4.0D, "S1", "Friday");
             return localDefaultCategoryDataset;
         }
     
         private static JFreeChart createChart(CategoryDataset paramCategoryDataset) {
             JFreeChart localJFreeChart = ChartFactory.createBarChart3D("Cylinder Chart Demo 2", "Category", "Value", paramCategoryDataset, PlotOrientation.HORIZONTAL, false, true, false);
             CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
             localCategoryPlot.setRangePannable(true);
             Paint[] arrayOfPaint = createPaint();
             CustomCylinderRenderer localCustomCylinderRenderer = new CustomCylinderRenderer(arrayOfPaint);
             localCustomCylinderRenderer.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_VERTICAL));
             localCustomCylinderRenderer.setBaseOutlinePaint(Color.gray);
             localCustomCylinderRenderer.setBaseOutlineStroke(new BasicStroke(0.3F));
             localCustomCylinderRenderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
             localCategoryPlot.setRenderer(localCustomCylinderRenderer);
             ChartUtilities.applyCurrentTheme(localJFreeChart);
             return localJFreeChart;
         }
     
         private static Paint[] createPaint() {
             Paint[] arrayOfPaint = new Paint[5];
             arrayOfPaint[0] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.red);
             arrayOfPaint[1] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.green);
             arrayOfPaint[2] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.blue);
             arrayOfPaint[3] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.orange);
             arrayOfPaint[4] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.magenta);
             return arrayOfPaint;
         }
     
         public static JPanel createDemoPanel() {
             JFreeChart localJFreeChart = createChart(createDataset());
             ChartPanel localChartPanel = new ChartPanel(localJFreeChart);
             localChartPanel.setMouseWheelEnabled(true);
             return localChartPanel;
         }
     
         public static void main(String[] paramArrayOfString) {
             CylinderChartDemo2 localCylinderChartDemo2 = new CylinderChartDemo2("CylinderChartDemo2.java");
             localCylinderChartDemo2.pack();
             RefineryUtilities.centerFrameOnScreen(localCylinderChartDemo2);
             localCylinderChartDemo2.setVisible(true);
         }
     
         static class CustomCylinderRenderer extends CylinderRenderer {
     
             private Paint[] colors;
     
             public CustomCylinderRenderer(Paint[] paramArrayOfPaint) {
                 this.colors = paramArrayOfPaint;
             }
     
             public Paint getItemPaint(int paramInt1, int paramInt2) {
                 return this.colors[(paramInt2 % this.colors.length)];
             }
         }
     }
```

  *s29.postimg.org/538tckb4j/Cylinder_Chart_Demo2.jpg

  Here is a Layered bar chart demo!!
  LayeredBarChartDemo2.java


```
/**
   *
   * @author Jguru
   */
  import java.awt.Color;
  import java.awt.Dimension;
  import java.awt.GradientPaint;
  import java.awt.Toolkit;
  import javax.swing.JPanel;
  import org.jfree.chart.ChartFactory;
  import org.jfree.chart.ChartPanel;
  import org.jfree.chart.JFreeChart;
  import org.jfree.chart.axis.NumberAxis;
  import org.jfree.chart.plot.CategoryPlot;
  import org.jfree.chart.plot.PlotOrientation;
  import org.jfree.chart.renderer.category.LayeredBarRenderer;
  import org.jfree.data.category.CategoryDataset;
  import org.jfree.data.category.DefaultCategoryDataset;
  import org.jfree.ui.ApplicationFrame;
  import org.jfree.ui.RefineryUtilities;
  import org.jfree.util.SortOrder;
  
  public class LayeredBarChartDemo2 extends ApplicationFrame {
  
      public LayeredBarChartDemo2(String paramString) {
          super(paramString);
          JPanel localJPanel = createDemoPanel();
          Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
          localJPanel.setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height / 2));
          setContentPane(localJPanel);
      }
  
      private static CategoryDataset createDataset() {
          String str1 = "First";
          String str2 = "Second";
          String str3 = "Third";
          String str4 = "Category 1";
          String str5 = "Category 2";
          String str6 = "Category 3";
          String str7 = "Category 4";
          String str8 = "Category 5";
          DefaultCategoryDataset localDefaultCategoryDataset = new DefaultCategoryDataset();
          localDefaultCategoryDataset.addValue(1.0D, str1, str4);
          localDefaultCategoryDataset.addValue(4.0D, str1, str5);
          localDefaultCategoryDataset.addValue(3.0D, str1, str6);
          localDefaultCategoryDataset.addValue(5.0D, str1, str7);
          localDefaultCategoryDataset.addValue(5.0D, str1, str8);
          localDefaultCategoryDataset.addValue(5.0D, str2, str4);
          localDefaultCategoryDataset.addValue(7.0D, str2, str5);
          localDefaultCategoryDataset.addValue(6.0D, str2, str6);
          localDefaultCategoryDataset.addValue(8.0D, str2, str7);
          localDefaultCategoryDataset.addValue(4.0D, str2, str8);
          localDefaultCategoryDataset.addValue(4.0D, str3, str4);
          localDefaultCategoryDataset.addValue(3.0D, str3, str5);
          localDefaultCategoryDataset.addValue(2.0D, str3, str6);
          localDefaultCategoryDataset.addValue(3.0D, str3, str7);
          localDefaultCategoryDataset.addValue(6.0D, str3, str8);
          return localDefaultCategoryDataset;
      }
  
      private static JFreeChart createChart(CategoryDataset paramCategoryDataset) {
          JFreeChart localJFreeChart = ChartFactory.createBarChart("Layered Bar Chart Demo 2", "Category", "Value", paramCategoryDataset, PlotOrientation.HORIZONTAL, true, true, false);
          CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
          localCategoryPlot.setDomainGridlinesVisible(true);
          localCategoryPlot.setRangePannable(true);
          localCategoryPlot.setRangeZeroBaselineVisible(true);
          NumberAxis localNumberAxis = (NumberAxis) localCategoryPlot.getRangeAxis();
          localNumberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
          LayeredBarRenderer localLayeredBarRenderer = new LayeredBarRenderer();
          localLayeredBarRenderer.setDrawBarOutline(false);
          localCategoryPlot.setRenderer(localLayeredBarRenderer);
          localCategoryPlot.setRowRenderingOrder(SortOrder.DESCENDING);
          GradientPaint localGradientPaint1 = new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 64));
          GradientPaint localGradientPaint2 = new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 64, 0));
          GradientPaint localGradientPaint3 = new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0));
          localLayeredBarRenderer.setSeriesPaint(0, localGradientPaint1);
          localLayeredBarRenderer.setSeriesPaint(1, localGradientPaint2);
          localLayeredBarRenderer.setSeriesPaint(2, localGradientPaint3);
          return localJFreeChart;
      }
  
      public static JPanel createDemoPanel() {
          JFreeChart localJFreeChart = createChart(createDataset());
          ChartPanel localChartPanel = new ChartPanel(localJFreeChart);
          localChartPanel.setMouseWheelEnabled(true);
          return localChartPanel;
      }
  
      public static void main(String[] paramArrayOfString) {
          LayeredBarChartDemo2 localLayeredBarChartDemo2 = new LayeredBarChartDemo2("LayeredBarChartDemo2");
          localLayeredBarChartDemo2.pack();
          RefineryUtilities.centerFrameOnScreen(localLayeredBarChartDemo2);
          localLayeredBarChartDemo2.setVisible(true);
      }
  }
```

  *s27.postimg.org/itd1jsgpr/Layered_Bar_Chart_Demo2.jpg

  PieChart3DDemo1.java


```
import java.awt.Dimension;
  import java.awt.Toolkit;
  import org.jfree.chart.ChartFactory;
  import org.jfree.chart.ChartPanel;
  import org.jfree.chart.JFreeChart;
  import org.jfree.chart.plot.PiePlot3D;
  import org.jfree.data.general.DefaultPieDataset;
  import org.jfree.data.general.PieDataset;
  import org.jfree.ui.ApplicationFrame;
  import org.jfree.ui.RefineryUtilities;
  import org.jfree.util.Rotation;
  
  public class PieChart3DDemo1 extends ApplicationFrame
  {
    public PieChart3DDemo1(String paramString)
    {
      super(paramString);
      ChartPanel localChartPanel = createDemoPanel();
      Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
      localChartPanel.setPreferredSize(new Dimension(scrDim.width/2, scrDim.height/2));
      setContentPane(localChartPanel);
    }
  
    private static PieDataset createDataset()
    {
      DefaultPieDataset localDefaultPieDataset = new DefaultPieDataset();
      localDefaultPieDataset.setValue("Java", new Double(43.200000000000003D));
      localDefaultPieDataset.setValue("Visual Basic", new Double(10.0D));
      localDefaultPieDataset.setValue("C/C++", new Double(17.5D));
      localDefaultPieDataset.setValue("PHP", new Double(32.5D));
      localDefaultPieDataset.setValue("Perl", null);
      return localDefaultPieDataset;
    }
  
    private static JFreeChart createChart(PieDataset paramPieDataset)
    {
      JFreeChart localJFreeChart = ChartFactory.createPieChart3D("Pie Chart 3D Demo 1", paramPieDataset, true, true, false);
      PiePlot3D localPiePlot3D = (PiePlot3D)localJFreeChart.getPlot();
      localPiePlot3D.setDarkerSides(true);
      localPiePlot3D.setStartAngle(290.0D);
      localPiePlot3D.setDirection(Rotation.CLOCKWISE);
      localPiePlot3D.setForegroundAlpha(0.5F);
      localPiePlot3D.setNoDataMessage("No data to display");
      return localJFreeChart;
    }
  
    public static ChartPanel createDemoPanel()
    {
      JFreeChart localJFreeChart = createChart(createDataset());
      ChartPanel localChartPanel = new ChartPanel(localJFreeChart);
      localChartPanel.setMouseWheelEnabled(true);
      return localChartPanel;
    }
  
    public static void main(String[] paramArrayOfString)
    {
      PieChart3DDemo1 localPieChart3DDemo1 = new PieChart3DDemo1("PieChart3DDemo1.java");
      localPieChart3DDemo1.pack();
      RefineryUtilities.centerFrameOnScreen(localPieChart3DDemo1);
      localPieChart3DDemo1.setVisible(true);
    }
  }
```

  *s8.postimg.org/8u12t0q8h/Pie_Chart3_DDemo1.jpg

  Here is a Stacked BarChart 


```
import java.awt.BasicStroke;
  import java.awt.Color;
  import java.awt.Dimension;
  import java.awt.Toolkit;
  import javax.swing.JPanel;
  import org.jfree.chart.ChartFactory;
  import org.jfree.chart.ChartPanel;
  import org.jfree.chart.JFreeChart;
  import org.jfree.chart.labels.ItemLabelAnchor;
  import org.jfree.chart.labels.ItemLabelPosition;
  import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
  import org.jfree.chart.plot.CategoryPlot;
  import org.jfree.chart.plot.IntervalMarker;
  import org.jfree.chart.plot.PlotOrientation;
  import org.jfree.chart.renderer.category.BarRenderer;
  import org.jfree.data.category.CategoryDataset;
  import org.jfree.data.category.DefaultCategoryDataset;
  import org.jfree.ui.ApplicationFrame;
  import org.jfree.ui.RefineryUtilities;
  import org.jfree.ui.TextAnchor;
  
  public class StackedBarChart3DDemo1 extends ApplicationFrame {
  
      private static final long serialVersionUID = 1L;
  
      public StackedBarChart3DDemo1(String paramString) {
          super(paramString);
          JPanel localJPanel = createDemoPanel();
          Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
          localJPanel.setPreferredSize(new Dimension(scrDim.width / 2, scrDim.height / 2));
          setContentPane(localJPanel);
      }
  
      public static CategoryDataset createDataset() {
          DefaultCategoryDataset localDefaultCategoryDataset = new DefaultCategoryDataset();
          localDefaultCategoryDataset.addValue(10.0D, "Series 1", "C1");
          localDefaultCategoryDataset.addValue(5.0D, "Series 1", "C2");
          localDefaultCategoryDataset.addValue(6.0D, "Series 1", "C3");
          localDefaultCategoryDataset.addValue(7.0D, "Series 1", "C4");
          localDefaultCategoryDataset.addValue(8.0D, "Series 1", "C5");
          localDefaultCategoryDataset.addValue(9.0D, "Series 1", "C6");
          localDefaultCategoryDataset.addValue(10.0D, "Series 1", "C7");
          localDefaultCategoryDataset.addValue(11.0D, "Series 1", "C8");
          localDefaultCategoryDataset.addValue(3.0D, "Series 1", "C9");
          localDefaultCategoryDataset.addValue(4.0D, "Series 2", "C1");
          localDefaultCategoryDataset.addValue(7.0D, "Series 2", "C2");
          localDefaultCategoryDataset.addValue(17.0D, "Series 2", "C3");
          localDefaultCategoryDataset.addValue(15.0D, "Series 2", "C4");
          localDefaultCategoryDataset.addValue(6.0D, "Series 2", "C5");
          localDefaultCategoryDataset.addValue(8.0D, "Series 2", "C6");
          localDefaultCategoryDataset.addValue(9.0D, "Series 2", "C7");
          localDefaultCategoryDataset.addValue(13.0D, "Series 2", "C8");
          localDefaultCategoryDataset.addValue(7.0D, "Series 2", "C9");
          localDefaultCategoryDataset.addValue(15.0D, "Series 3", "C1");
          localDefaultCategoryDataset.addValue(14.0D, "Series 3", "C2");
          localDefaultCategoryDataset.addValue(12.0D, "Series 3", "C3");
          localDefaultCategoryDataset.addValue(11.0D, "Series 3", "C4");
          localDefaultCategoryDataset.addValue(10.0D, "Series 3", "C5");
          localDefaultCategoryDataset.addValue(0.0D, "Series 3", "C6");
          localDefaultCategoryDataset.addValue(7.0D, "Series 3", "C7");
          localDefaultCategoryDataset.addValue(9.0D, "Series 3", "C8");
          localDefaultCategoryDataset.addValue(11.0D, "Series 3", "C9");
          localDefaultCategoryDataset.addValue(14.0D, "Series 4", "C1");
          localDefaultCategoryDataset.addValue(3.0D, "Series 4", "C2");
          localDefaultCategoryDataset.addValue(7.0D, "Series 4", "C3");
          localDefaultCategoryDataset.addValue(0.0D, "Series 4", "C4");
          localDefaultCategoryDataset.addValue(9.0D, "Series 4", "C5");
          localDefaultCategoryDataset.addValue(6.0D, "Series 4", "C6");
          localDefaultCategoryDataset.addValue(7.0D, "Series 4", "C7");
          localDefaultCategoryDataset.addValue(9.0D, "Series 4", "C8");
          localDefaultCategoryDataset.addValue(10.0D, "Series 4", "C9");
          return localDefaultCategoryDataset;
      }
  
      private static JFreeChart createChart(CategoryDataset paramCategoryDataset) {
          JFreeChart localJFreeChart = ChartFactory.createStackedBarChart3D("Stacked Bar Chart 3D Demo 1", "Category", "Value", paramCategoryDataset, PlotOrientation.VERTICAL, true, true, false);
          CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
          IntervalMarker localIntervalMarker = new IntervalMarker(5.0D, 10.0D, Color.gray, new BasicStroke(0.5F), Color.blue, new BasicStroke(0.5F), 0.5F);
          localCategoryPlot.addRangeMarker(localIntervalMarker);
          BarRenderer localBarRenderer = (BarRenderer) localCategoryPlot.getRenderer();
          localBarRenderer.setDrawBarOutline(false);
          localBarRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
          localBarRenderer.setBaseItemLabelsVisible(true);
          localBarRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
          localBarRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
          return localJFreeChart;
      }
  
      public static JPanel createDemoPanel() {
          JFreeChart localJFreeChart = createChart(createDataset());
          return new ChartPanel(localJFreeChart);
      }
  
      public static void main(String[] paramArrayOfString) {
          StackedBarChart3DDemo1 localStackedBarChart3DDemo1 = new StackedBarChart3DDemo1("Stacked Bar Chart 3D Demo 1");
          localStackedBarChart3DDemo1.pack();
          RefineryUtilities.centerFrameOnScreen(localStackedBarChart3DDemo1);
          localStackedBarChart3DDemo1.setVisible(true);
      }
  }
```

  *s27.postimg.org/6l3ymjycf/Stacked_Bar_Chart3_DDemo1.jpg

  For a complete list of all the demos see *Charting Guide using JFreeChart* *www.digit.in/forum/programming/187235-charting-guide-using-jfreechart.html

  Q) What is OOPS (Object-Oriented Programming System)?

  Ans. 

  OOPS was invented because procedural languages such as C, Pascal, BASIC were found to be inadequate for large and complex programs.
  One difficulty with this kind of function-based organisation was it focussed on functions at the expense of data. The data could be
  local to the function or it could be global. This caused problems when several functions needed to access the same data. To be available 
  to more than one function , such variables had to be global, but global data could be accessed inadvertently by any functionin he program.
  This lead to frequent program errors!!

*Objects*
  Here is the amazing breakthrough that is key to OOP. An object contains functions and variables. A Thermostat object would contain not
  only furnaceOn() and furnaceOff() functions, but also currentTemp and desiredTemp. Incidentally in Java , functions are called methods and
  variables are called fields.

  Ths new entity, the Object solves sveral problems simultaneously. Not only does a Programming object correspond more accurately to objects in the real world, it also
  solves the problem engendered by global data in the procedural model.


```
class Thermostat {
  
      private float currentTemp;
      private float desiredTemp;
      
      public void furnaceOn() {
         // mehod body goes here    
      }
      
      public void furnaceOff() {
             // mehod body goes here    
      }
      
  } // End class Thermostat
```
 
*Object-Oriented Programming Concepts*

  What Is an Object?

  Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

  Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

  Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

  Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

  By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.

  Bundling code into individual software objects provides a number of benefits, including:

      Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

      Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

      Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

      Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

  What Is a Class?

  In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

  The following Bicycle class is one possible implementation of a bicycle:


```
class Bicycle {
  
      int cadence = 0;
      int speed = 0;
      int gear = 1;
  
      void changeCadence(int newValue) {
           cadence = newValue;
      }
  
      void changeGear(int newValue) {
           gear = newValue;
      }
  
      void speedUp(int increment) {
           speed = speed + increment;   
      }
  
      void applyBrakes(int decrement) {
           speed = speed - decrement;
      }
  
      void printStates() {
           System.out.println("cadence:" +
               cadence + " speed:" + 
               speed + " gear:" + gear);
      }
  }
```
 
  The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

  You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.

  Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:


```
class BicycleDemo {
      public static void main(String[] args) {
  
          // Create two different 
          // Bicycle objects
          Bicycle bike1 = new Bicycle();
          Bicycle bike2 = new Bicycle();
  
          // Invoke methods on 
          // those objects
          bike1.changeCadence(50);
          bike1.speedUp(10);
          bike1.changeGear(2);
          bike1.printStates();
  
          bike2.changeCadence(50);
          bike2.speedUp(10);
          bike2.changeGear(2);
          bike2.changeCadence(40);
          bike2.speedUp(10);
          bike2.changeGear(3);
          bike2.printStates();
      }
  }
```
 
  The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

  cadence:50 speed:10 gear:2
  cadence:40 speed:20 gear:3

  Here are the books you can study to understand OOPS & apply it !!


  1) Object-oriented Programming in C++ by Robert Lafore (Waite Group, 1995)

  2) Object-Oriented Design Heuristics by Arthur J Riel (Addison Wesley)

  3) An Introduction to Object-Oriented Programming by Timothy Budd (Addison Wesley 1996)

  4) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty 

  5) Beginning Java Objects (Wrox)

  6) Big Java Late Objects by Cay S. Horstmann 

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

  8) Object-oriented Analysis and Design with Applications by Grady Booch (Addison Wesley , 1994)

  9) The Object Primer : The Application Developer's Guide to Object-Orientation by Scott W Ambler

  10) Design Patterns : Elements of Reusable Object-Oriented Software by Erich Gamma et al (Addison Wesley)

  11) Object-Oriented Programming in Java by Balagurusamy

  12) C++ with OOPS by Balagurusamy

  Q) What is Java2D ?

  Ans. The Java 2D™ API provides two-dimensional graphics, text, and imaging capabilities for Java™ programs through extensions to the Abstract Windowing Toolkit (AWT). This comprehensive 
  rendering package supports line art, text, and images in a flexible, full-featured framework for developing richer user interfaces, sophisticated drawing programs, and image editors. 
  Java 2D objects exist on a plane called user coordinate space, or just user space. When objects are rendered on a screen or a printer, user space coordinates are transformed to 
  device space coordinates.

  To see Java2D in action see *Java2D Graphics Guide* link: *www.digit.in/forum/programming/188347-java2d-graphics-guide.html

  To learn more about Java2D study the book Java 2D API Graphics by Vincent Hardy

  Q) How can I play MP3 music in Java?

  Ans. You can play MP3 music in Java using JMF (Java Media Framework) , JavaFX, JLayer, QuickTime for Java.

  Here is demo that plays MP3 using JMF


```
// MusicPlayer.java
// There must a file called test.wav in the current directory
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class MusicPlayer extends JFrame implements ControllerListener
{
   Component cc, vc;
   Player player;
   String URL = "";
   Container contn;
   private String filename = "test.wav";

   MusicPlayer (String title)
   {
      super (title);
      URL = "file://" + new File(filename).getAbsolutePath();
      contn = getContentPane();
      contn.add(new GraphicDisplay(), BorderLayout.NORTH);
      try
      {
         player = Manager.createPlayer (new MediaLocator(URL));
         player.start();
      }
      catch (java.io.IOException e)
      {
         terminate (e.toString ());
      }
      catch (NoPlayerException e)
      {
         terminate ("Could not find a player.");
      }

      if (player == null)
          terminate ("Trouble creating player.");

      player.addControllerListener (this);
      player.prefetch ();
   }

   public void controllerUpdate (ControllerEvent e)
   {
      if (e instanceof ControllerClosedEvent)
          System.exit (0);

      if (e instanceof EndOfMediaEvent)
      {
          player.setMediaTime (new Time (0));
          GraphicDisplay.gRunner.stop();
          return;
      }

      if (e instanceof RealizeCompleteEvent)
      {
          vc = player.getVisualComponent ();
          if (vc != null)
          {
              contn.add (vc, BorderLayout.CENTER);
          }

          cc = player.getControlPanelComponent ();
          if (cc != null)
              contn.add (cc, (vc != null) ? BorderLayout.SOUTH
                                    : BorderLayout.CENTER);

          setSize(305, 316);
          setResizable(false);
          setVisible (true);
          setTitle("Java Media Player Demo");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
   }

   void terminate (String s)
   {
      System.out.println (s);
      System.exit (-1);
   }

   public static void main (String [] args)
   {
      new MusicPlayer ("Music Player");
   }
}
```

   *s3.postimg.org/tqsi4dzan/Music_Player.jpg

  Remember you need to install JMF first & include the file jmf.jar & fobs4jmf.jar in your CLASSPATH, or copy it to the ext folder.

  Here is another demo using Apple's QuickTime for Java that plays a QuickTime format video!!


```
/**
   *
   * @author JGuru
   */
  import java.awt.FileDialog;
  import java.awt.Frame;
  import java.awt.event.ActionListener;
  import java.awt.event.WindowAdapter;
  import java.awt.event.WindowEvent;
  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import quicktime.QTException;
  import quicktime.io.QTFile;
  import quicktime.std.movies.Movie;
  
  //  Can't load IA 32-bit .dll on a AMD 64-bit platform on Java JDK 7 64-bit Error!!!
  // This works only with 32-bit JDK!!
  public class SimpleMoviePlayer
          extends JFrame
          implements quicktime.std.StdQTConstants,
          quicktime.Errors,
          quicktime.io.IOConstants {
      private static final long serialVersionUID = 1L;
  
      public static void main(String args[]) {
          try {
              // Required to initialize the QuickTime environment.
              // Performs checks to ensure QuickTime is installed and
              // also loads and sets up QuickTime.
              quicktime.QTSession.open();
  
              SimpleMoviePlayer myPlayer = new SimpleMoviePlayer("Simple Player");
  
              myPlayer.pack();
              myPlayer.setVisible(true);
              myPlayer.toFront();
          } catch (QTException e) {
              quicktime.QTSession.close();
          }
      }
  
      /* ------------------- User interface ------------------------------------ */
      JButton importButton = new JButton("Import Media...");
      JButton referenceButton = new JButton("Export Reference Media...");
      JButton exportButton = new JButton("Export Full Media...");
      JPanel commandPanel = new JPanel();
      JLabel statusLabel = new JLabel("Ready.");
  
      // The QTCanvas is the "heavy lifter" QuickTime component
      // that does all the hard work for punching the QuickTime
      // viewer through and into the JFrame.
      quicktime.app.display.QTCanvas myQTCanvas;
  
      /* Creates the application user interface. You'll
       * notice that there is no reference to new user interface
       * options for QuickTime features - those are controlled by
       * the "punched through" QuickTime capabilities.
       */
      SimpleMoviePlayer(String title) {
          super(title);
  
          getContentPane().add(statusLabel, "North");
  
          importButton.addActionListener(new ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent ae) {
                  importMedia();
              }
          });
          commandPanel.add(importButton);
  
          referenceButton.addActionListener(new ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent ae) {
                  makeReferenceMovie();
              }
          });
          commandPanel.add(referenceButton);
  
          exportButton.addActionListener(new ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent ae) {
                  exportMovie();
              }
          });
  
          commandPanel.add(exportButton);
  
          this.getContentPane().add(commandPanel, "South");
  
          addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  // Go ahead and clean up the QuickTime layer
                  quicktime.QTSession.close();
                  dispose();
              }
  
              public void windowClosed(WindowEvent e) {
                  System.exit(0);
              }
          });
      }
  
      /* ------------------------- Importing Media ------------------------------- */
      public void importMedia() {
          try {
              FileDialog myFileDialog
                      = new FileDialog(this, "Choose Media to Import...", FileDialog.LOAD);
  
              myFileDialog.show();
  
              if (myFileDialog.getFile() == null) {
                  return;
              }
  
              QTFile importFile
                      = new QTFile(myFileDialog.getDirectory() + myFileDialog.getFile());
  
              // You can import any supported media type into QuickTime using
              // the QTFactory.
              // QTFactory.makeDrawable(  ) methods take a variety of inputs,
              // from URLs to an InputStream, and produce a usable media object.
              // The media object might represent a sound file (such as an MP3),
              // a picture (such as a GIF), or a full movie (such as a
              // QuickTime .mov)
              quicktime.app.display.QTDrawable media = null;
  
              try {
                  media = quicktime.app.QTFactory.makeDrawable(importFile);
              } catch (quicktime.QTException qtException) {
                  // If not a user cancel, go ahead and report error
                  if (qtException.getMessage().indexOf("cantFindHandler") > 0) {
                      qtException.printStackTrace();
                  } else {
                      java.awt.Toolkit.getDefaultToolkit().beep();
                      statusLabel.setText("Unable to open this file type.");
                  }
              }
  
              if (media != null) {
                  if (myQTCanvas == null) {
                      myQTCanvas = new quicktime.app.display.QTCanvas();
                      this.getContentPane().add(myQTCanvas, "Center");
                  }
                  myQTCanvas.setClient(media, true);
                  statusLabel.setText(importFile.getPath());
  
                  // This resizes the UI. Note that the "preferred" size
                  // for myQTCanvas has been changed to whatever works for
                  // the player.
                  pack();
              }
          } catch (QTException err) {
              if (err.errorCode() == userCanceledErr) {
                  return;
              }
              err.printStackTrace();
          } catch (java.io.IOException ie) {
          }
      }
  
      /* ------------------------- Playing Movies ------------------------------- */
      public void displayMovie(Movie m) throws QTException {
          // make a QTPlayer out of the Movie and set it as the 
          // client of the QTCanvas
  
          quicktime.app.players.QTPlayer p
                  = new quicktime.app.players.QTPlayer(
                  new quicktime.std.movies.MovieController(m)
                  );
  
          if (myQTCanvas == null) {
              myQTCanvas = new quicktime.app.display.QTCanvas();
              getContentPane().add(myQTCanvas, "Center");
          }
  
          myQTCanvas.setClient(p, true);
          pack();
      }
  
      /* ------------------------ QuickTime References ------------------------ */
      public void makeReferenceMovie() {
          try {
              FileDialog rfd
                      = new FileDialog(this, "Choose Movie to Reference...", FileDialog.LOAD);
              rfd.setVisible(true);
  
              if (rfd.getFile() == null) {
                  return;
              }
  
              QTFile movieFile = new QTFile(rfd.getDirectory() + rfd.getFile());
  
              FileDialog ofd
                      = new FileDialog(this, "New Movie to create...", FileDialog.SAVE);
  
              ofd.show();
  
              if (ofd.getFile() == null) {
                  return;
              }
  
              makeReferenceMovie(movieFile, ofd.getDirectory() + ofd.getFile());
          } catch (QTException err) {
              if (err.errorCode() == userCanceledErr) {
                  return;
              }
              err.printStackTrace();
          }
      }
  
      //makes a new movie that references the data in an existing movie
      public void makeReferenceMovie(QTFile movieFile, String outputPath)
              throws QTException {
  
          // Create the movie object from the original movie
          Movie theMovie = Movie.fromFile(quicktime.io.OpenMovieFile.asRead(movieFile));
  
          displayMovie(theMovie);
          QTFile outputMovie = new QTFile(outputPath);
  
          //shortcut movies are movies that just contain a reference
          //to another movie.  It can begin to be complicated for users
          //to track which is which - you may wish to expose a flag
          //indicating handles to movies as opposed to flattened
          //movies in your user interface.
          //make a Data ref out of a URL that references the movie
          quicktime.std.movies.media.DataRef targetDataRef
                  = new quicktime.std.movies.media.DataRef("file://" + movieFile.getPath());
  
          //make the very small short cut movie
          outputMovie.createShortcutMovieFile(
                  kMoviePlayer, smSystemScript, createMovieFileDeleteCurFile, targetDataRef);
      }
  
  
      /* ------------------------ Exporting Movies ------------------------ */
      public void exportMovie() {
          try {
  
              FileDialog efd
                      = new FileDialog(this, "Choose Movie to Export...", FileDialog.LOAD);
  
              efd.setVisible(true);
  
              if (efd.getFile() == null) {
                  return;
              }
  
              QTFile movieFile = new QTFile(efd.getDirectory() + efd.getFile());
  
              exportMovie(movieFile);
          } catch (QTException err) {
              err.printStackTrace();
          }
      }
  
      // export (to a movie) the incoming movie
      // user dialog allows user to customise media formats and 
      // tracks that are exported
      public void exportMovie(QTFile movieFile) throws QTException {
          // Create the movie object from the original movie
          Movie theMovie
                  = Movie.fromFile(quicktime.io.OpenMovieFile.asRead(movieFile));
  
          displayMovie(theMovie);
  
          // we do this in a different thread because exporting can take some time
          // and the event thread should not be blocked for so long... but it tends
          // to really drag the UI anyways on Mac OS X for serious exporting.
          new Thread(
                  new com.sowndar.media.qt.SimpleMoviePlayer.Runner(
                  theMovie, statusLabel)
                  ).start();
  
      }
  
      static class Runner implements Runnable {
  
          Runner(Movie mov, JLabel inStatus) {
              theInputMovie = mov;
              status = inStatus;
          }
  
          Movie theInputMovie;
          JLabel status;
  
          public void run() {
  
              try {
                  // this determines both the exporter type, the resulting file type.
                  // thus one could specify this to be AIFF and the resulting file will 
                  // be an AIFF file - in this case the result will be a movie.
  
                  int exportType = kQTFileTypeMovie;
  
                  //an application can alternatively configure exporter through setting
                  //up the exporter in code to conform to the format appropriate
                  FileDialog ofd
                          = new FileDialog(new Frame(), "Export Movie to...", FileDialog.SAVE);
                  ofd.setVisible(true);
                  if (ofd.getFile() == null) {
                      return;
                  }
  
                  QTFile outFile = new QTFile(ofd.getDirectory() + ofd.getFile());
  
                  // Create a movie exporter so we can customise its settings
                  // this could also be used in the convertToFile version, but
                  // if we don't have custom settings then we allow the convertToFile
                  // to create the exporter for us-based on the exportType we pass to it
                  quicktime.std.qtcomponents.MovieExporter theMovieExp
                          = new quicktime.std.qtcomponents.MovieExporter(exportType);
  
                  // Set export settings from the user.
                  theMovieExp.doUserDialog(
                          theInputMovie, null, 0, theInputMovie.getDuration());
                   /*
                   //this returns a dupFNErr on windows and is also more work for 
                   //the application create the output file but don't open it
                   outFile.createMovieFile(kMoviePlayer,
                   status.setText("Starting export...");
                   // do the export of the movie
                   theMovieExp.toFile(
                   outFile, theInputMovie, null, 0, theInputMovie.getDuration());
                   status.setText("Export complete.");
                   */
              } catch (QTException e) {
                  e.printStackTrace();
              }
          }
      }
  }
```

   *s30.postimg.org/j02v8e9kd/Simple_Movie_Player.jpg

  After launching the program, click on the 'Import Media...' button & select the QuickTime Video & click on the play button, to play the video.

  Here is another demo!!


```
import java.io.*;
  import javax.swing.*;
  // Importing QuickTime for Java API classes
  import quicktime.std.*;
  import quicktime.std.clocks.*;
  import quicktime.std.movies.*;
  import quicktime.*;
  import quicktime.io.*;
  import quicktime.app.time.*;
  
  public class QTJSound extends Object {
  
      File soundFile;
      JDialog playingDialog;
      Movie movie;
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
  
              public void run() {
                  JFileChooser chooser = new JFileChooser();
                  chooser.showOpenDialog(null);
                  File file = chooser.getSelectedFile();
                  if (file != null) {
                      try {
                          QTJSound s = new QTJSound(file);
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  } else {
                      JOptionPane.showMessageDialog(null, "Oops, You didn't select a audio file!!", "Info", JOptionPane.INFORMATION_MESSAGE);
                  }
              }
          });
      }
  
      public QTJSound(File f)
              throws QTException {
          soundFile = f;
          // prepare a dialog to display while playing
          JOptionPane pane = new JOptionPane("Playing " + f.getName(),
                  JOptionPane.PLAIN_MESSAGE);
          playingDialog = pane.createDialog(null, "QTJ Sound");
          playingDialog.pack();
  
          // get and play sound
          QTSession.open();
          QTFile qtf = new QTFile(f);
          OpenMovieFile omf = OpenMovieFile.asRead(qtf);
          movie = Movie.fromFile(omf);
          MyDemoCloser closer = new MyDemoCloser(movie);
          TaskAllMovies.addMovieAndStart();
          // Start playing the media file
          movie.start();
          playingDialog.setVisible(true);
      }
  
      class MyDemoCloser extends ExtremesCallBack {
  
          public MyDemoCloser(Movie m) throws QTException {
              super(m.getTimeBase(),
                      StdQTConstants.triggerAtStop);
              callMeWhen();
          }
  
          public void execute() {
              playingDialog.setVisible(false);
              System.out.println("dialog closed");
              // note: this can hang on Windows - consider
              // using QTSession.exitMovies() instead
              QTSession.close();
              System.out.println("closed QTSession");
              System.exit(0);
          }
      }
  }
```

  You must Install Apple's QuickTime & include the file "QTJava.zip" in you CLASSPATH or copy it to the ext folder.
  Remember QuickTime for Java uses native libraries, that means it's only works in Windows & Mac OS. Since QuickTime's libraries are 32-bit, it
  only works with 32-bit JDK, not 64-bit JDK!!


  Here is another demo that uses JavaFX to play multimedia files (MP3, MPEG, Flash etc.,)


```
import java.io.File;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * An advanced media player with controls for play/pause, seek, and volume.
 *
 *   [MENTION=288550]see[/MENTION] javafx.scene.media.MediaPlayer
 *   [MENTION=288550]see[/MENTION] javafx.scene.media.Media
 */
public class AdvancedMedia extends Application {

    private MediaPlayer mediaPlayer;
    // Create a directory called 'resources' & place a file called 'Dangerous.mp3' in it. (Michael Jackson's 'Dangerous' album)
    private static String filename = "resources/Dangerous.mp3";
    private static String path = "file:///" + new File(filename).getAbsolutePath();
    private static String MEDIA_URL;

    private void init(Stage primaryStage) {

        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        path = path.replace('\\', '/');
        MEDIA_URL = path;
        mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
        mediaPlayer.setAutoPlay(true);
        MediaControl mediaControl = new MediaControl(mediaPlayer);
        mediaControl.setMinSize(480 * 2, 280 * 2);
        mediaControl.setPrefSize(480 * 2, 280 * 2);
        mediaControl.setMaxSize(800, 600);
        root.getChildren().add(mediaControl);
    }

    public void play() {
        Status status = mediaPlayer.getStatus();
        if (status == Status.UNKNOWN
                || status == Status.HALTED) {
            //System.out.println("Player is in a bad or unknown state, can't play.");
            return;
        }

        if (status == Status.PAUSED
                || status == Status.STOPPED
                || status == Status.READY) {
            mediaPlayer.play();
        }
    }

    @Override
    public void stop() {
        mediaPlayer.stop();
    }

    public class MediaControl extends BorderPane {

        private MediaPlayer mp;
        private MediaView mediaView;
        private final boolean repeat = false;
        private boolean stopRequested = false;
        private boolean atEndOfMedia = false;
        private Duration duration;
        private Slider timeSlider;
        private Label playTime;
        private Slider volumeSlider;
        private HBox mediaBar;
        private final Image PlayButtonImage = new Image(AdvancedMedia.class.getResourceAsStream("playbutton.png"));
        private final Image PauseButtonImage = new Image(AdvancedMedia.class.getResourceAsStream("pausebutton.png"));
        ImageView imageViewPlay = new ImageView(PlayButtonImage);
        ImageView imageViewPause = new ImageView(PauseButtonImage);
        private Pane mvPane;
        private Stage newStage;
        private boolean fullScreen = false;

        @Override
        protected void layoutChildren() {
            if (mediaView != null && getBottom() != null) {
                mediaView.setFitWidth(getWidth());
                mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
            }
            super.layoutChildren();
            if (mediaView != null && getCenter() != null) {
                mediaView.setTranslateX((((Pane) getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
                mediaView.setTranslateY((((Pane) getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
            }
        }

        @Override
        protected double computeMinWidth(double height) {
            return mediaBar.prefWidth(-1);
        }

        @Override
        protected double computeMinHeight(double width) {
            return 200;
        }

        @Override
        protected double computePrefWidth(double height) {
            return Math.max(mp.getMedia().getWidth(), mediaBar.prefWidth(height));
        }

        @Override
        protected double computePrefHeight(double width) {
            return mp.getMedia().getHeight() + mediaBar.prefHeight(width);
        }

        @Override
        protected double computeMaxWidth(double height) {
            return Double.MAX_VALUE;
        }

        @Override
        protected double computeMaxHeight(double width) {
            return Double.MAX_VALUE;
        }

        public MediaControl(final MediaPlayer mp) {
            this.mp = mp;
            setStyle("-fx-background-color: #bfc2c7;"); // TODO: Use css file
            mediaView = new MediaView(mp);
            mvPane = new Pane();
            mvPane.getChildren().add(mediaView);
            mvPane.setStyle("-fx-background-color: black;"); // TODO: Use css file
            setCenter(mvPane);
            mediaBar = new HBox(5.0);
            mediaBar.setPadding(new Insets(5, 10, 5, 10));
            mediaBar.setAlignment(Pos.CENTER_LEFT);
            BorderPane.setAlignment(mediaBar, Pos.CENTER);

            final Button playButton = ButtonBuilder.create()
                    .minWidth(Control.USE_PREF_SIZE)
                    .build();

            playButton.setGraphic(imageViewPlay);
            playButton.setOnAction(new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e) {
                    updateValues();
                    Status status = mp.getStatus();
                    if (status == Status.UNKNOWN
                            || status == Status.HALTED) {
                        // don't do anything in these states
                        return;
                    }

                    if (status == Status.PAUSED
                            || status == Status.READY
                            || status == Status.STOPPED) {
                        // rewind the movie if we're sitting at the end
                        if (atEndOfMedia) {
                            mp.seek(mp.getStartTime());
                            atEndOfMedia = false;
                            playButton.setGraphic(imageViewPlay);
                            //playButton.setText(">");
                            updateValues();
                        }
                        mp.play();
                        playButton.setGraphic(imageViewPause);
                        //playButton.setText("||");
                    } else {
                        mp.pause();
                    }
                }
            });
            mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
                @Override
                public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
                    updateValues();
                }
            });
            mp.setOnPlaying(new Runnable() {
                public void run() {

                    if (stopRequested) {
                        mp.pause();
                        stopRequested = false;
                    } else {
                        playButton.setGraphic(imageViewPause);
                        //playButton.setText("||");
                    }
                }
            });
            mp.setOnPaused(new Runnable() {
                public void run() {

                    playButton.setGraphic(imageViewPlay);
                    //playButton.setText("||");
                }
            });
            mp.setOnReady(new Runnable() {
                public void run() {
                    duration = mp.getMedia().getDuration();
                    updateValues();
                }
            });

            mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
            mp.setOnEndOfMedia(new Runnable() {
                public void run() {
                    if (!repeat) {
                        playButton.setGraphic(imageViewPlay);
                        //playButton.setText(">");
                        stopRequested = true;
                        atEndOfMedia = true;
                    }
                }
            });
            mediaBar.getChildren().add(playButton);

            // Time label
            Label timeLabel = new Label("Time");
            timeLabel.setMinWidth(Control.USE_PREF_SIZE);
            mediaBar.getChildren().add(timeLabel);

            // Time slider
            timeSlider = SliderBuilder.create()
                    .minWidth(30)
                    .maxWidth(Double.MAX_VALUE)
                    .build();
            HBox.setHgrow(timeSlider, Priority.ALWAYS);
            timeSlider.valueProperty().addListener(new InvalidationListener() {
                public void invalidated(Observable ov) {
                    if (timeSlider.isValueChanging()) {
                        // multiply duration by percentage calculated by slider position
                        if (duration != null) {
                            mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
                        }
                        updateValues();

                    }
                }
            });
            mediaBar.getChildren().add(timeSlider);

            // Play label
            playTime = LabelBuilder.create()
                    //.prefWidth(130)
                    .minWidth(Control.USE_PREF_SIZE)
                    .build();

            mediaBar.getChildren().add(playTime);

            //Fullscreen button
            Button buttonFullScreen = ButtonBuilder.create()
                    .text("Full Screen")
                    .minWidth(Control.USE_PREF_SIZE)
                    .build();

            buttonFullScreen.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    if (!fullScreen) {
                        newStage = new Stage();
                        newStage.fullScreenProperty().addListener(new ChangeListener<Boolean>() {
                            @Override
                            public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                                onFullScreen();
                            }
                        });
                        final BorderPane borderPane = new BorderPane() {
                            @Override
                            protected void layoutChildren() {
                                if (mediaView != null && getBottom() != null) {
                                    mediaView.setFitWidth(getWidth());
                                    mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
                                }
                                super.layoutChildren();
                                if (mediaView != null) {
                                    mediaView.setTranslateX((((Pane) getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
                                    mediaView.setTranslateY((((Pane) getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
                                }
                            }
                        ;
                        };

                    setCenter(null);
                        setBottom(null);
                        borderPane.setCenter(mvPane);
                        borderPane.setBottom(mediaBar);

                        Scene newScene = new Scene(borderPane);
                        newStage.setScene(newScene);
                        //Workaround for disposing stage when exit fullscreen
                        newStage.setX(-100000);
                        newStage.setY(-100000);

                        newStage.setFullScreen(true);
                        fullScreen = true;
                        newStage.show();

                    } else {
                        //toggle FullScreen
                        fullScreen = false;
                        newStage.setFullScreen(false);

                    }
                }

            });
            mediaBar.getChildren().add(buttonFullScreen);

            // Volume label
            Label volumeLabel = new Label("Vol");
            volumeLabel.setMinWidth(Control.USE_PREF_SIZE);
            mediaBar.getChildren().add(volumeLabel);

            // Volume slider
            volumeSlider = SliderBuilder.create()
                    .prefWidth(70)
                    .minWidth(30)
                    .maxWidth(Region.USE_PREF_SIZE)
                    .build();
            volumeSlider.valueProperty().addListener(new InvalidationListener() {
                public void invalidated(Observable ov) {
                }
            });
            volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                    if (volumeSlider.isValueChanging()) {
                        mp.setVolume(volumeSlider.getValue() / 100.0);
                    }
                }
            });
            mediaBar.getChildren().add(volumeSlider);

            setBottom(mediaBar);

        }

        protected void onFullScreen() {
            if (!newStage.isFullScreen()) {

                fullScreen = false;
                setCenter(mvPane);
                setBottom(mediaBar);
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        newStage.close();
                    }
                });

            }
        }

        protected void updateValues() {
            if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
                Platform.runLater(new Runnable() {
                    public void run() {
                        Duration currentTime = mp.getCurrentTime();
                        playTime.setText(formatTime(currentTime, duration));
                        timeSlider.setDisable(duration.isUnknown());
                        if (!timeSlider.isDisabled() && duration.greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
                            timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
                        }
                        if (!volumeSlider.isValueChanging()) {
                            volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
                        }
                    }
                });
            }
        }

        private String formatTime(Duration elapsed, Duration duration) {
            int intElapsed = (int) Math.floor(elapsed.toSeconds());
            int elapsedHours = intElapsed / (60 * 60);
            if (elapsedHours > 0) {
                intElapsed -= elapsedHours * 60 * 60;
            }
            int elapsedMinutes = intElapsed / 60;
            int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;

            if (duration.greaterThan(Duration.ZERO)) {
                int intDuration = (int) Math.floor(duration.toSeconds());
                int durationHours = intDuration / (60 * 60);
                if (durationHours > 0) {
                    intDuration -= durationHours * 60 * 60;
                }
                int durationMinutes = intDuration / 60;
                int durationSeconds = intDuration - durationHours * 60 * 60 - durationMinutes * 60;

                if (durationHours > 0) {
                    return String.format("%d:%02d:%02d/%d:%02d:%02d",
                            elapsedHours, elapsedMinutes, elapsedSeconds,
                            durationHours, durationMinutes, durationSeconds);
                } else {
                    return String.format("%02d:%02d/%02d:%02d",
                            elapsedMinutes, elapsedSeconds,
                            durationMinutes, durationSeconds);
                }
            } else {
                if (elapsedHours > 0) {
                    return String.format("%d:%02d:%02d",
                            elapsedHours, elapsedMinutes, elapsedSeconds);
                } else {
                    return String.format("%02d:%02d",
                            elapsedMinutes, elapsedSeconds);
                }
            }
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
        play();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     *   [MENTION=9956]PARAM[/MENTION] args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}
```

*s27.postimg.org/gw36f6w5b/Advanced_Media.jpg

Use JLayer (*www.javazoom.net/javalayer/javalayer.html) to play MP3 files in Java.
Use the JAR file 'jl1.0.1.jar' in the classpath or add it to the ext directory.
Alternatively those using a IDE like NetBeans, Eclipse, IDEA can create a library called 'JLayer' add the JAR file to the library.
Add the library to the Project.

Here is a sample code.


```
import java.applet.Applet;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javazoom.jl.decoder.JavaLayerException;

/**
 * A simple applet that plays an MPEG audio file. 
 * The URL (relative to the document base)
 * is passed as the "audioURL" parameter. 
 * 
 * @author	Mat McGowan
 * @since	0.0.8
 */
public class PlayerApplet extends Applet implements Runnable
{
	static public final String AUDIO_PARAMETER = "audioURL";
	
	/**
	 * The Player used to play the MPEG audio file. 
	 */
	private Player	player = null;
	
	/**
	 * The thread that runs the player.
	 */
	private Thread	playerThread = null;	
	
	private String	fileName = null;
	
	
	/**
	 * Retrieves the <code>AudioDevice</code> instance that will
	 * be used to sound the audio data. 
	 * 
	 * @return	an audio device instance that will be used to 
	 *			sound the audio stream.
	 */
	protected AudioDevice getAudioDevice() throws JavaLayerException
	{
		return FactoryRegistry.systemRegistry().createAudioDevice();
	}
	
	/**
	 * Retrieves the InputStream that provides the MPEG audio
	 * stream data. 
	 * 
	 * @return	an InputStream from which the MPEG audio data
	 *			is read, or null if an error occurs. 
	 */
	protected InputStream getAudioStream()
	{
		InputStream in = null;
		
		try
		{
			URL url = getAudioURL();
			if (url!=null)			
				in = url.openStream();
		}
		catch (IOException ex)
		{
			System.err.println(ex);
		}
		return in;
	}

	protected String getAudioFileName()
	{
		String urlString = fileName;
		if (urlString==null)
		{
			urlString = getParameter(AUDIO_PARAMETER);
		}
		return urlString;
	}
	
	protected URL getAudioURL()
	{				
		String urlString = getAudioFileName();
		URL url = null;
		if (urlString!=null)
		{
			try
			{
				url = new URL(getDocumentBase(), urlString);				
			}
			catch (Exception ex)
			{
				System.err.println(ex);	
			}
		}		
		return url;
	}
	
	/**
	 * Sets the URL of the audio stream to play.
	 */
	public void setFileName(String name)
	{
		fileName = name;
	}
	
	public String getFileName()
	{
		return fileName;	
	}
	
	/**
	 * Stops the audio player. If the player is already stopped
	 * this method is a no-op.  
	 */
	protected void stopPlayer() throws JavaLayerException
	{
		if (player!=null)
		{
			player.close();
			player = null;
			playerThread = null;
		}
	}
	
	/**
	 * Decompresses audio data from an InputStream and plays it
	 * back through an AudioDevice. The playback is run on a newly
	 * created thread. 
	 * 
	 *   [MENTION=9956]PARAM[/MENTION] in	The InputStream that provides the MPEG audio data.
	 *   [MENTION=9956]PARAM[/MENTION] dev	The AudioDevice to use to sound the decompressed data. 
	 * 
	 * @throws JavaLayerException if there was a problem decoding
	 *		or playing the audio data.
	 */
	protected void play(InputStream in, AudioDevice dev) throws JavaLayerException
	{
		stopPlayer();
		
		if (in!=null && dev!=null)
		{
			player = new Player(in, dev);
			playerThread = createPlayerThread();
			playerThread.start();
		}
	}
	
	/**
	 * Creates a new thread used to run the audio player.
	 * @return A new Thread that, once started, runs the audio player.
	 */
	protected Thread createPlayerThread()
	{
		return new Thread(this, "Audio player thread");	
	}
	
	/**
	 * Initializes this applet.
	 */
	public void init()
	{		
	}
	
	/**
	 * Starts this applet. An input stream and audio device 
	 * are created and passed to the play() method.
	 */
	public void start()
	{
		String name = getAudioFileName();
		try
		{			
			InputStream in = getAudioStream();
			AudioDevice dev = getAudioDevice();
			play(in, dev);
		}
		catch (JavaLayerException ex)
		{
			synchronized (System.err)
			{
				System.err.println("Unable to play "+name);
				ex.printStackTrace(System.err);
			}
		}
	}	
	
	/**
	 * Stops this applet. If audio is currently playing, it is
	 * stopped.
	 */
	public void stop()
	{
		try
		{
			stopPlayer();
		}
		catch (JavaLayerException ex)
		{
			System.err.println(ex);
		}
	}
	
	public void destroy()
	{
	}
	
	/**
	 * The run method for the audio player thread. Simply calls
	 * play() on the player to play the entire stream. 
	 */
	public void run()
	{				
		if (player!=null)
		{
			try
			{
				player.play();				
			}
			catch (JavaLayerException ex)
			{
				System.err.println("Problem playing audio: "+ex);
			}			
		}
	}
}
```
 

```
import java.io.InputStream;
 import javazoom.jl.decoder.Bitstream;
 import javazoom.jl.decoder.BitstreamException;
 import javazoom.jl.decoder.Decoder;
 import javazoom.jl.decoder.Header;
 import javazoom.jl.decoder.JavaLayerException;
 import javazoom.jl.decoder.SampleBuffer;
 import javazoom.jl.player.AudioDevice;
 import javazoom.jl.player.FactoryRegistry;
 
 /**
  * a hybrid of javazoom.jl.player.Player tweeked to include
  * <code>play(startFrame, endFrame)</code> hopefully this will be included in
  * the api
  */
 public class AdvancedPlayer {
 
     /**
      * The MPEG audio bit stream.
      */
     private Bitstream bitstream;
     /**
      * The MPEG audio decoder.
      */
     private Decoder decoder;
     /**
      * The AudioDevice the audio samples are written to.
      */
     private AudioDevice audio;
     /**
      * Has the player been closed?
      */
     private boolean closed = false;
     /**
      * Has the player played back all frames from the stream?
      */
     private boolean complete = false;
     private int lastPosition = 0;
     /**
      * Listener for the playback process
      */
     private PlaybackListener listener;
 
     /**
      * Creates a new
      * <code>Player</code> instance.
      */
     public AdvancedPlayer(InputStream stream) throws JavaLayerException {
         this(stream, null);
     }
 
     public AdvancedPlayer(InputStream stream, AudioDevice device) throws JavaLayerException {
         bitstream = new Bitstream(stream);
 
         if (device != null) {
             audio = device;
         } else {
             audio = FactoryRegistry.systemRegistry().createAudioDevice();
         }
         audio.open(decoder = new Decoder());
     }
 
     public void play() throws JavaLayerException {
         play(Integer.MAX_VALUE);
     }
 
     /**
      * Plays a number of MPEG audio frames.
      *
      *   [MENTION=9956]PARAM[/MENTION] frames	The number of frames to play.
      * @return	true if the last frame was played, or false if there are more
      * frames.
      */
     public boolean play(int frames) throws JavaLayerException {
         boolean ret = true;
 
         // report to listener
         if (listener != null) {
             listener.playbackStarted(createEvent(PlaybackEvent.STARTED));
         }
 
         while (frames-- > 0 && ret) {
             ret = decodeFrame();
         }
 
 
         {
             // last frame, ensure all data flushed to the audio device.
             AudioDevice out = audio;
             if (out != null) {
                     //  System.out.println(audio.getPosition());
                 out.flush();
                     //	System.out.println(audio.getPosition());
                 synchronized (this) {
                     complete = (!closed);
                     close();
                 }
 
                 // report to listener
                 if (listener != null) {
                     listener.playbackFinished(createEvent(out, PlaybackEvent.STOPPED));
                 }
             }
         }
         return ret;
     }
 
     /**
      * Closes this player. Any audio currently playing is stopped immediately.
      */
     public synchronized void close() {
         AudioDevice out = audio;
         if (out != null) {
             closed = true;
             audio = null;
             // this may fail, so ensure object state is set up before
             // calling this method.
             out.close();
             lastPosition = out.getPosition();
             try {
                 bitstream.close();
             } catch (BitstreamException ex) {
             }
         }
     }
 
     /**
      * Decodes a single frame.
      *
      * @return true if there are no more frames to decode, false otherwise.
      */
     protected boolean decodeFrame() throws JavaLayerException {
         try {
             AudioDevice out = audio;
             if (out == null) {
                 return false;
             }
 
             Header h = bitstream.readFrame();
             if (h == null) {
                 return false;
             }
 
             // sample buffer set when decoder constructed
             SampleBuffer output = (SampleBuffer) decoder.decodeFrame(h, bitstream);
 
             synchronized (this) {
                 out = audio;
                 if (out != null) {
                     out.write(output.getBuffer(), 0, output.getBufferLength());
                 }
             }
 
             bitstream.closeFrame();
         } catch (RuntimeException ex) {
             throw new JavaLayerException("Exception decoding audio frame", ex);
         }
         return true;
     }
 
     /**
      * skips over a single frame
      *
      * @return false	if there are no more frames to decode, true otherwise.
      */
     protected boolean skipFrame() throws JavaLayerException {
         Header h = bitstream.readFrame();
         if (h == null) {
             return false;
         }
         bitstream.closeFrame();
         return true;
     }
 
     /**
      * Plays a range of MPEG audio frames
      *
      *   [MENTION=9956]PARAM[/MENTION] start	The first frame to play
      *   [MENTION=9956]PARAM[/MENTION] end	The last frame to play
      * @return true if the last frame was played, or false if there are more
      * frames.
      */
     public boolean play(final int start, final int end) throws JavaLayerException {
         boolean ret = true;
         int offset = start;
         while (offset-- > 0 && ret) {
             ret = skipFrame();
         }
         return play(end - start);
     }
 
     /**
      * Constructs a
      * <code>PlaybackEvent</code>
      */
     private PlaybackEvent createEvent(int id) {
         return createEvent(audio, id);
     }
 
     /**
      * Constructs a
      * <code>PlaybackEvent</code>
      */
     private PlaybackEvent createEvent(AudioDevice dev, int id) {
         return new PlaybackEvent(this, id, dev.getPosition());
     }
 
     /**
      * sets the
      * <code>PlaybackListener</code>
      */
     public void setPlayBackListener(PlaybackListener listener) {
         this.listener = listener;
     }
 
     /**
      * gets the
      * <code>PlaybackListener</code>
      */
     public PlaybackListener getPlayBackListener() {
         return listener;
     }
 
     /**
      * closes the player and notifies
      * <code>PlaybackListener</code>
      */
     public void stop() {
         listener.playbackFinished(createEvent(PlaybackEvent.STOPPED));
         close();
     }
 }
```
 
 Q) How can I play other media formats like VCD, DVD, Windows media video (WMV) using Java?

 Ans. Use SWT that embeds Windows Media Player (only works in Windows)


```
/*
  * To change this license header, choose License Headers in Project Properties.
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
 /**
  *
  * @author Sowndar
  */
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.SWTError;
 import org.eclipse.swt.events.SelectionAdapter;
 import org.eclipse.swt.events.SelectionEvent;
 import org.eclipse.swt.layout.FillLayout;
 import org.eclipse.swt.ole.win32.*;
 import org.eclipse.swt.widgets.*;
 
 /*
  * Open an OLE Windows Media Player.
  *
  * For a list of all SWT example snippets see
  * *www.eclipse.org/swt/snippets/
  *
  * @since 3.3
  */
 //Error :  java.lang.UnsatisfiedLinkError: Cannot load 32-bit SWT libraries on 64-bit JVM
 // Ofcourse you can run this program only in Windows OS, since it uses it's native media player!!
 public class SWTMediaPlayer {
 
     static OleClientSite clientSite;
 
     public static void main(String[] args) {
         Display display = new Display();
         Shell shell = new Shell(display);
         shell.setText("SWTMediaPlayer");
         shell.setLayout(new FillLayout());
         try {
             OleFrame frame = new OleFrame(shell, SWT.NONE);
             clientSite = new OleClientSite(frame, SWT.NONE, "WMPlayer.OCX");
             clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
             addFileMenu(frame);
         } catch (SWTError e) {
             System.out.println("Unable to open activeX control");
             display.dispose();
             return;
         }
         shell.setSize(800, 600);
         shell.open();
         while (!shell.isDisposed()) {
             if (!display.readAndDispatch()) {
                 display.sleep();
             }
         }
         display.dispose();
     }
 
     static void addFileMenu(OleFrame frame) {
         final Shell shell = frame.getShell();
         Menu menuBar = shell.getMenuBar();
         if (menuBar == null) {
             menuBar = new Menu(shell, SWT.BAR);
             shell.setMenuBar(menuBar);
         }
         MenuItem fileMenu = new MenuItem(menuBar, SWT.CASCADE);
         fileMenu.setText("&File");
         Menu menuFile = new Menu(fileMenu);
         fileMenu.setMenu(menuFile);
         frame.setFileMenus(new MenuItem[]{fileMenu});
 
         MenuItem menuFileOpen = new MenuItem(menuFile, SWT.CASCADE);
         menuFileOpen.setText("Open...");
         menuFileOpen.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
                 fileOpen();
             }
         });
         MenuItem menuFileExit = new MenuItem(menuFile, SWT.CASCADE);
         menuFileExit.setText("Exit");
         menuFileExit.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
                 shell.dispose();
             }
         });
     }
 
     static void fileOpen() {
         FileDialog dialog = new FileDialog(clientSite.getShell(), SWT.OPEN);
         // Set file filter
         dialog.setFilterExtensions(new String[]{"*.mov"});
         String filename = dialog.open();
         if (filename != null) {
             OleAutomation player = new OleAutomation(clientSite);
             int playURL[] = player.getIDsOfNames(new String[]{"URL"});
             if (playURL != null) {
                 Variant theFile = new Variant(filename);
                 player.setProperty(playURL[0], theFile);
             }
             player.dispose();
         }
     }
 }
```

  *s4.postimg.org/sl6uujg7t/SWTMedia_Player.jpg

  Q) What is VolatileImage ?

  Ans. VolatileImage is an image which can lose its contents at any time due to circumstances beyond the control of the application (e.g., situations caused by the operating system or by other applications). Because of the potential for hardware acceleration, a VolatileImage 
  object can have significant performance benefits on some platforms.
  The drawing surface of an image (the memory where the image contents actually reside) can be lost or invalidated, causing the contents of that memory to go away. The drawing surface thus needs to be restored or recreated and the contents of that surface need to be re-rendered.
  VolatileImage provides an interface for allowing the user to detect these problems and fix them when they occur. 

  Here is a demo that uses VolatileImage to draw the animation of the Images.


```
/**
   * Created with IntelliJ IDEA.
   * User: Sowndar
   * Date: 9/30/14
   * Time: 8:01 PM
   * To change this template use File | Settings | File Templates.
   */
  
  import javax.imageio.ImageIO;
  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.MouseAdapter;
  import java.awt.event.MouseEvent;
  import java.awt.image.BufferedImage;
  import java.awt.image.VolatileImage;
  import java.io.File;
  import java.io.FilenameFilter;
  import java.io.IOException;
  import java.util.Date;
  import java.util.Random;
  
  public class VolatileBufferedAnimator extends JWindow {
  
      private ImageRenderer[] pics;
      private boolean running = true;
      private VolatileImage buffer;
      //Create an array of Strings
      private static String[] images;
      // NOTE : You need to create a directory called 'Images' and place some JPG, PNG, BMP Images there
      private String path = "Images/";
  
      public VolatileBufferedAnimator() {
          super(new Frame());
          images = new File(path).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;
              }
          });
          GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
          GraphicsDevice screen = ge.getDefaultScreenDevice();
  
          if (!screen.isFullScreenSupported()) {
              throw new IllegalStateException("Full screen mode not supported");
          }
  
          pics = new ImageRenderer[images.length];
  
          for (int a = 0; a < images.length; a++) {
              try {
                  BufferedImage pic = ImageIO.read(new File(path + images[a]));
                  pics[a] = new ImageRenderer(pic, screen, this);
              } catch (IOException e) {
                  System.out.println("Exception Raised! : " + e);
              }
          }
  
          buffer = screen.getDefaultConfiguration()
                  .createCompatibleVolatileImage(
                          screen.getDisplayMode().getWidth(),
                          screen.getDisplayMode().getHeight());
  
          setBackground(Color.BLACK);
          screen.setFullScreenWindow(this);
  
          addMouseListener(new MouseAdapter() {
              @Override
              public void mouseClicked(MouseEvent e) {
                  synchronized (VolatileBufferedAnimator.this) {
                      stop();
                      dispose();
                      System.exit(0);
                  }
              }
          });
      }
  
      private synchronized void stop() {
          running = false;
      }
  
      private synchronized boolean isRunning() {
          return running;
      }
  
      public void animate() {
          new Thread(new Runnable() {
  
              @Override
              public void run() {
                  while (isRunning()) {
                      render();
                  }
              }
          }).start();
      }
  
      public synchronized void render() {
          do {
              buffer.validate(getGraphicsConfiguration());
              Graphics2D g = buffer.createGraphics();
              g.setBackground(Color.BLACK);
              g.clearRect(0, 0, getWidth(), getHeight());
              for (int a = 0; a < pics.length; a++) {
                  pics[a].render(g);
              }
          } while (buffer.contentsLost());
          getGraphics().drawImage(buffer, 0, 0,
                  getWidth(), getHeight(), this);
      }
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
  
              @Override
              public void run() {
                  new VolatileBufferedAnimator().animate();
              }
          });
      }
  }
  
  
  class ImageRenderer {
  
      private static final int MAX_HEIGHT = 300;
      private static final int MAX_WIDTH = 300;
  
      private static final int MIN_PERIOD = 6000;
      private static final int MAX_PERIOD = 60000;
  
      private int baseWidth;
      private int baseHeight;
      private int screenWidth;
      private int screenHeight;
      private int maxWidth;
      private int maxHeight;
      private long startTime;
      private BufferedImage pic;
  
      private int xperiod;
      private int yperiod;
      private int zoomperiod;
  
      private Random rand;
  
      private Window window;
  
      ImageRenderer(BufferedImage pic, GraphicsDevice screen, Window window) {
          this.pic = pic;                // the image we will render
          this.window = window;             // the window we will render to
          baseWidth = pic.getWidth();     // the width of the picture
          baseHeight = pic.getHeight();    // the height of the picture
          screenWidth = screen.getDisplayMode().getWidth();
          // the width of the screen
          screenHeight = screen.getDisplayMode().getHeight();
          // the height of the screen
          startTime = new Date().getTime(); // the current number of
          // milliseconds since 1970
          rand = new Random();              // A source of randomness
  
          // Calculate the maximum size for this image,
          // preserving aspect ratio
          double aspect = ((double) baseWidth) / ((double) baseHeight);
          maxWidth = baseWidth;
          maxHeight = baseHeight;
  
          if (maxWidth > MAX_WIDTH) {
              maxWidth = MAX_WIDTH;
              maxHeight = (int) (((double) MAX_WIDTH) / aspect);
          } else {
              //Setting the minimum width
              maxWidth = 250;
              maxHeight = (int) (((double) maxWidth) / aspect);
          }
  
          if (maxHeight > MAX_HEIGHT) {
              maxHeight = MAX_HEIGHT;
              maxWidth = (int) (((double) MAX_HEIGHT) * aspect);
          } else {
              //Setting the minimum height
              maxHeight = 250;
              maxWidth = (int) (((double) maxHeight) * aspect);
          }
          // choose random periods for movement and size
  
          xperiod = rand.nextInt(MAX_PERIOD - MIN_PERIOD) + MIN_PERIOD;
          yperiod = rand.nextInt(MAX_PERIOD - MIN_PERIOD) + MIN_PERIOD;
          zoomperiod = rand.nextInt(MAX_PERIOD - MIN_PERIOD) + MIN_PERIOD;
      }
  
      void render(Graphics2D g) {
  
          // obtain zoom, horizontal and vertical deflections
          double zoomFactor = getFactor(zoomperiod);
          double xFactor = getFactor(xperiod);
          double yFactor = getFactor(yperiod);
  
          // calculate image size
          int width = (int) (maxWidth * zoomFactor);
          int height = (int) (maxHeight * zoomFactor);
  
          // calculate position
          int maxX = screenWidth - width;
          int x = (int) (maxX * xFactor);
  
          int maxY = screenHeight - height;
          int y = (int) (maxY * yFactor);
  
          // display the image
          g.drawImage(pic, x, y, width, height, window);
      }
  
      private double getFactor(int period) {
          long time = new Date().getTime();
          double n = ((double) time) / ((double) period);
          double s = Math.sin(n * Math.PI * 2);
          return s * s;
      }
  }
```

  *s1.postimg.org/p5v3cdfmz/Volatile_Buffered_Animator.jpg

  Q) What is MemoryImageSource ?

  Ans. This class is an implementation of the ImageProducer interface which uses an array to produce pixel values for an Image.


```
/*
   * To change this template, choose Tools | Templates
   * and open the template in the editor.
   */
  /**
   *
   * @author sowndar
   */
  import java.awt.BorderLayout;
  import java.awt.Dimension;
  import java.awt.Image;
  import java.awt.Toolkit;
  import java.awt.image.MemoryImageSource;
  import javax.swing.ImageIcon;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.SwingUtilities;
  
  //MemoryImageSource : This class is an implementation of the ImageProducer interface which uses an array to produce pixel values for an Image.
  public class MemoryImageGenerator extends JFrame {
  
      private Image image;
      private JLabel label = new JLabel();
  
      public MemoryImageGenerator() {
          Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
          int width = scrDim.width;
          int height = scrDim.height;
          int pixels[] = new int[width * height];
          int i = 0;
          // Fill the entire region with the Image pattern
          for (int y = 0; y < height; y++) {
              for (int x = 0; x < width; x++) {
                  int red = (x ^ y) & 0xff;
                  int green = (x * 2 ^ y * 2) & 0xff;
                  int blue = (x * 4 ^ y * 4) & 0xff;
                  pixels[i++] = (255 << 24) | (red << 16) | (green << 8) | blue;
              }
          }
          image = createImage(new MemoryImageSource(width, height, pixels, 0, width));
          label.setIcon(new ImageIcon(image));
          add(label, BorderLayout.CENTER);
          setSize(scrDim.width / 2, scrDim.height);
          setTitle("Memory Image Source");
          setVisible(true);
          setDefaultCloseOperation(MemoryImageGenerator.EXIT_ON_CLOSE);
      }
  
      public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
  
              @Override
              public void run() {
                  new MemoryImageGenerator();
              }
          });
      }
  }
```

  [img=*s24.postimg.org/f2w6pqqyp/Memory_Image_Generator.jpg]

  Q) How can I read a Word document using Java ?

  Ans. Use Apache POI to read a MS Word document using Java language.

  Q) What is JavaFX ?

  Ans. JavaFX is a scripting language like Adobe's Flash. JavaFX can be embedded in Swing to play mutimedia files.
  JavaFx is available from JDK1.7 onwards. It's also cross-platform.

  Q) How can I read & write Adobe's PDF format using Java ?

  Ans. You can read & write PDF format using iText's library. Download it from here *sourceforge.net/projects/itext/files/

  Here is demo the demonstrates reading a PDF using iText


```
import java.io.IOException;
//iText imports
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

// NOTE : You must have a directory called resources & a file called test.pdf under that directory.
public class iTextReadDemo {

	/**
	 *   [MENTION=9956]PARAM[/MENTION] args
	 */
	public static void main(String[] args) {
        try {
        	
		PdfReader reader = new PdfReader("resources/test.pdf");
		System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
	        String page = PdfTextExtractor.getTextFromPage(reader, 2);
	        System.out.println("Page Content:\n\n"+page+"\n\n");
	        System.out.println("Is this document tampered: "+reader.isTampered());
	        System.out.println("Is this document encrypted: "+reader.isEncrypted());

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

	}

}
```


 Here is another demo that shows how to write PDF using iText


```
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

public class JavaWritePDF {

	/**
	 *   [MENTION=9956]PARAM[/MENTION] args
	 */
	public static void main(String[] args) {
		try {
			File file = new File("itext.pdf");
			FileOutputStream pdfFileout = new FileOutputStream(file);
			Document doc = new Document();
			PdfWriter.getInstance(doc, pdfFileout);

			doc.addAuthor("JGuru");
			doc.addTitle("This is title");
			doc.open();

			Paragraph para1 = new Paragraph();
			para1.add("This is paragraph 1");

			Paragraph para2 = new Paragraph();
			para2.add("This is paragraph 2");

			doc.add(para1);
			doc.add(para2);

			doc.close();
			pdfFileout.close();

			System.out.println("Success!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
```
 
 Remember you need to include itextpdf-5.4.3.jar in your CLASSPATH or copy it to the ext folder.

  Those using a IDE like NetBeans, IDEA, Eclipse can create a library called 'iTextPDF-5.4.3'  & include it in the project settings.
 Those interested in developing a full-fledged PDF Viewer must read the book iText in Action ( available from www.amazon.in) 

 Q) What are books I need to study to write a Project using .NET framework?

*Books for Programming in .NET*:

  1) Head First C#, 2E: A Learner's Guide to Real-World Programming with Visual C# and .NET by Andrew Stellman and Jennifer Greene

  2) Beginning Visual C# 2012 Programming by Karli Watson, Jacob Vibe Hammer, Jon Reid and Morgan Skinner 

  3) Visual C# 2012 How to Program (5th Edition) by Paul Deitel and Harvey Deitel 

  4) C# Design Pattern Essentials by Tony Bevis

  5) Professional C# 2012 and .NET 4.5 by Christian Nagel, Bill Evjen, Jay Glynn and Karli Watson 

  6) Beginning ASP.NET 4.5: in C# and VB by Imar Spaanjaars

  7) Professional ASP.NET 4.5 in C# and VB by Jason N. Gaylord, Christian Wenz, Pranav Rastogi, Todd Miranda, Scott Hanselman

  8) Professional ASP.NET MVC 4 by Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen

  9) ASP.NET 3.5 Website Programming Problem - Design - Solution by Chris Love, Marco Bellinaso

  10) C# Bible (Wiley publishing)

  11) C# 5.0 Unleashed 

  12) SQL Server Bible

  These books are a must if you want to be a good .NET programmer!!!

  Head First -> Introduces you to programming in a easier way.

  Beginning Visual C# -> Gives you a good grounding of C# for a beginner in C# language.

  Visual C# How to program -> Helps you to solve problems using C# language

  C# Design patterns -> Introduces you to Object Oriented programming

  Professional C# -> Learn how to write real world programs in a professional manner

  Professional ASP.NET -> Teaches you to write ecommerce projects in .NET platform

  Professional ASP.NET MVC4 - > The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and 
 the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is 
 a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master 
 pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

  Read more about MVC here : *msdn.microsoft.com/en-us/library/dd381412(VS.98).aspx

  ASP.NET 3.5 -> Learn how to create, test & deploy web applications.

  C# Bible - > In-depth look at C# API with clear & good examples

  C# Unleashed : Covers the C# API in-depth

 These books are available from any good book store in your city. You can also buy them online from www.amazon.in

 Q) What can I do to become a better Java/C/C++/C# programmer ?

 Ans. See *Introduction to Programming in Java language* link :  *www.digit.in/forum/programming/187238-introduction-programming-java.html

Q) How can I display the Histogram for a Image ?

Ans. Here is the code!!


```
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class HistogramDemo extends JComponent {

    private BufferedImage image;
    private Histogram histogram;
    private boolean displayRGB = true;

    public HistogramDemo(String fileName) {
        //Get the Image
        image = getImage(fileName);
        if (image != null) {
            setImage(image);
            setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
        }
    }

    public void setImage(BufferedImage image) {
        if (image != null) {
            PixelGrabber pg = new PixelGrabber(image, 0, 0, -1, -1, null, 0, -1);
            try {
                pg.grabPixels();
            } catch (InterruptedException e) {
                throw new RuntimeException("interrupted waiting for pixels!");
            }
            if ((pg.status() & 0x80) != 0) {
                throw new RuntimeException("image fetch aborted");
            }
            histogram = new Histogram((int[]) pg.getPixels(), pg.getWidth(), pg.getHeight(), 0, pg.getWidth());
        }
    }

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

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        // Set the rendering hints
        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);

        // Draw the Image
        if (image != null) {
            g2d.drawImage(image, 0, 0, this);
        }

        int width = getWidth();
        int height = 275;
        int b = getHeight();
        width -= 20;

        // Draw the Histogram
        if (histogram != null) {

            if (displayRGB) {
                int max = 0;
                for (int channel = 0; channel <= 2; channel++) {
                    max = Math.max(histogram.getMaxFrequency(channel), 0);
                }
                g2d.setComposite(AlphaComposite.getInstance(3, 0.6F));
                for (int channel = 0; channel <= 2; channel++) {
                    g2d.setColor(channel == 1 ? Color.green : channel == 0 ? Color.red : Color.blue);
                    for (int x = 0; x < 256; x++) {
                        int y = histogram.getFrequency(channel, x) * height / max;
                        g2d.drawLine(x + 10, b, x + 10, b - y);
                    }
                }
            } else {

                g2d.setColor(Color.black);
                int channel = 0;
                int max = histogram.getMaxFrequency(channel);
                for (int x = 0; x < 256; x++) {
                    int y = histogram.getFrequency(channel, x) * height / max;
                    g2d.drawLine(x + 10, b, x + 10, b - y);
                }
            }
        }
    }

    public static void main(final String[] args) {
        if (args.length > 0) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    JFrame f = new JFrame("HistogramDemo");
                    f.add(new HistogramDemo(args[0]));
                    f.pack();
                    f.setVisible(true);
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
            });
        } else {
            System.out.println("java HistogramDemo <image path>");
        }
    }
}

/**
 * An image histogram.
 */
class Histogram {

    public static final int RED = 0;
    public static final int GREEN = 1;
    public static final int BLUE = 2;
    public static final int GRAY = 3;

    protected int[][] histogram;
    protected int numSamples;
    protected int[] minValue;
    protected int[] maxValue;
    protected int[] minFrequency;
    protected int[] maxFrequency;
    protected float[] mean;
    protected boolean isGray;

    public Histogram() {
        histogram = null;
        numSamples = 0;
        isGray = true;
        minValue = null;
        maxValue = null;
        minFrequency = null;
        maxFrequency = null;
        mean = null;
    }

    public Histogram(int[] pixels, int w, int h, int offset, int stride) {
        histogram = new int[3][256];
        minValue = new int[4];
        maxValue = new int[4];
        minFrequency = new int[3];
        maxFrequency = new int[3];
        mean = new float[3];

        numSamples = w * h;
        isGray = true;

        int index = 0;
        for (int y = 0; y < h; y++) {
            index = offset + y * stride;
            for (int x = 0; x < w; x++) {
                int rgb = pixels[index++];
                int r = (rgb >> 16) & 0xff;
                int g = (rgb >> 8) & 0xff;
                int b = rgb & 0xff;
                histogram[RED][r]++;
                histogram[GREEN][g]++;
                histogram[BLUE][b]++;
            }
        }

        for (int i = 0; i < 256; i++) {
            if (histogram[RED][i] != histogram[GREEN][i] || histogram[GREEN][i] != histogram[BLUE][i]) {
                isGray = false;
                break;
            }
        }

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 256; j++) {
                if (histogram[i][j] > 0) {
                    minValue[i] = j;
                    break;
                }
            }

            for (int j = 255; j >= 0; j--) {
                if (histogram[i][j] > 0) {
                    maxValue[i] = j;
                    break;
                }
            }

            minFrequency[i] = Integer.MAX_VALUE;
            maxFrequency[i] = 0;
            for (int j = 0; j < 256; j++) {
                minFrequency[i] = Math.min(minFrequency[i], histogram[i][j]);
                maxFrequency[i] = Math.max(maxFrequency[i], histogram[i][j]);
                mean[i] += (float) (j * histogram[i][j]);
            }
            mean[i] /= (float) numSamples;
        }
        minValue[GRAY] = Math.min(Math.min(minValue[RED], minValue[GREEN]), minValue[BLUE]);
        maxValue[GRAY] = Math.max(Math.max(maxValue[RED], maxValue[GREEN]), maxValue[BLUE]);
    }

    public boolean isGray() {
        return isGray;
    }

    public int getNumSamples() {
        return numSamples;
    }

    public int getFrequency(int value) {
        if (numSamples > 0 && isGray && value >= 0 && value <= 255) {
            return histogram[0][value];
        }
        return -1;
    }

    public int getFrequency(int channel, int value) {
        if (numSamples < 1 || channel < 0 || channel > 2
                || value < 0 || value > 255) {
            return -1;
        }
        return histogram[channel][value];
    }

    public int getMinFrequency() {
        if (numSamples > 0 && isGray) {
            return minFrequency[0];
        }
        return -1;
    }

    public int getMinFrequency(int channel) {
        if (numSamples < 1 || channel < 0 || channel > 2) {
            return -1;
        }
        return minFrequency[channel];
    }

    public int getMaxFrequency() {
        if (numSamples > 0 && isGray) {
            return maxFrequency[0];
        }
        return -1;
    }

    public int getMaxFrequency(int channel) {
        if (numSamples < 1 || channel < 0 || channel > 2) {
            return -1;
        }
        return maxFrequency[channel];
    }

    public int getMinValue() {
        if (numSamples > 0 && isGray) {
            return minValue[0];
        }
        return -1;
    }

    public int getMinValue(int channel) {
        return minValue[channel];
    }

    public int getMaxValue() {
        if (numSamples > 0 && isGray) {
            return maxValue[0];
        }
        return -1;
    }

    public int getMaxValue(int channel) {
        return maxValue[channel];
    }

    public float getMeanValue() {
        if (numSamples > 0 && isGray) {
            return mean[0];
        }
        return -1.0F;
    }

    public float getMeanValue(int channel) {
        if (numSamples > 0 && RED <= channel && channel <= BLUE) {
            return mean[channel];
        }
        return -1.0F;
    }
}
```

*s2.postimg.org/6zj3qoeut/Histogram_Demo.jpg

To run the program from the cmd-line, type:

java HistogramDemo <image path>

The program displays the Histogram on the lower left side of the Image.

Q) How can I fetch an Image from a URL ?

Ans. Use the URL class & the URLConnection class to connect to the URL & fetch it.

GetImage.java


```
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.net.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class GetImage {

    private String name;
    private JFrame f;
    private Image image;
    private Toolkit toolkit = Toolkit.getDefaultToolkit();
    private JLabel label = new JLabel();

    public static void main(String args[]) {
        if (args.length != 1) {
            System.out.println("Usage: java GetImage <image-URL>");
            System.exit(1);
        }
        GetImage that = new GetImage(args[0]);
        that.go();
    }

    public GetImage(String name) {
        this.name = name;
    }

    public void go() {
        Object o = null;
        f = new JFrame("Image from " + name);
        URL source = null;
        URLConnection con = null;

        try {
            source = new URL(name);
            o = source.getContent();
        } catch (IOException e) {
            System.out.println("Problem with URL " + source);
            System.exit(2);
        }

        if (o instanceof ImageProducer) {
            image = toolkit.createImage((ImageProducer) o);
        } else {
            System.out.println("URL " + source
                    + " didn't give me an ImageProducer");
            System.out.println("but a " + o.getClass().getName() + " instead");
            System.exit(3);
        }

        label.setIcon(new ImageIcon(image));
        f.add(new JScrollPane(label));
        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
```

To run this program, type:

java GetImage <URL>

Q) What is Java Swing ?

Ans. JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.

Q) What is Java Swing ?

Ans. JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.

To run the following programs create a directory called 'JSession' & place all the programs in that directory.
Also create a directory called 'Images' under the JSession directory & place the JPG, PNG, GIF, BMP pictures (a minimum of 10, a maximum of 20).
We need icons & Images to run the following programs. You can also use an IDE like NetBeans, IDEA, or JDeveloper to run this programs.

*JButton*

Ordinary buttons — JButton objects — have just a bit more functionality than the AbstractButton class provides: You can make a JButton be the default button.
When the size of the button component is larger than its contents, the label and icon are always kept together.
you can place the label/icon pair in one of nine possible locations. How you implement event handling depends on the type of button you use and how you use it. 
Generally, you implement an action listener, which is notified every time the user clicks the button.


```
// Place the contents in the nw corner
    button.setVerticalAlignment(SwingConstants.TOP);
    button.setHorizontalAlignment(SwingConstants.LEFT);
    
    // Place the contents centered at the top
    button.setVerticalAlignment(SwingConstants.TOP);
    button.setHorizontalAlignment(SwingConstants.CENTER);
    
    // Place the contents in the ne corner
    button.setVerticalAlignment(SwingConstants.BOTTOM);
    button.setHorizontalAlignment(SwingConstants.RIGHT);
    
    // Place the contents in the sw corner
    button.setVerticalAlignment(SwingConstants.BOTTOM);
    button.setHorizontalAlignment(SwingConstants.LEFT);
    
    // Place the contents centered at the bottom
    button.setVerticalAlignment(SwingConstants.BOTTOM);
    button.setHorizontalAlignment(SwingConstants.CENTER);
    
    // Place the contents in the se corner
    button.setVerticalAlignment(SwingConstants.BOTTOM);
    button.setHorizontalAlignment(SwingConstants.RIGHT);
    
    // Place the contents vertically centered on the left
    button.setVerticalAlignment(SwingConstants.CENTER);
    button.setHorizontalAlignment(SwingConstants.LEFT);
    
    // Place the contents directly in the center
    button.setVerticalAlignment(SwingConstants.CENTER);
    button.setHorizontalAlignment(SwingConstants.CENTER);
    
    // Place the contents vertically centered on the right
    button.setVerticalAlignment(SwingConstants.CENTER);
    button.setHorizontalAlignment(SwingConstants.RIGHT);
```

The following programs loads all the Images in the 'Images' directory & shows the Image preview using an array of buttons,
added to JPanel.


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 9/14/14
 * Time: 10:18 PM
 * To change this template use File | Settings | File Templates.
 */
// ThumbnailButtons.java
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import static java.lang.System.out;

// All the Image buttons are loaded with a graphic icon and then the Image preview is added later

public class ThumbnailButtons extends JFrame implements Runnable {

    private int iconWidth = 140;
    private int iconHeight = 110;
    private ImageIcon picIcon = new ImageIcon("Icons/image_64x64.png");
    private int columns = 8;
    private int rows;
    private Dimension scrDim;
    private String path = "Images/";
    private File directory = new File(path);
    private JLabel statusBar = new JLabel("Ready");

    @Override
    public void run() {
        loadImages();
    }

    public void loadImages() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            // Do nothing
        }
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();

        String[] name = directory.list(new FilenameFilter() {
            String[] readFormat = ImageIO.getReaderFormatNames();

            @Override
            public boolean accept(File dir, String name) {
                name = name.toLowerCase();
                for (int i = 0; i < readFormat.length; i++) {
                    if (name.endsWith(readFormat[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        int MAX = name.length;
        rows = MAX / columns;

        //Create that many Buttons
        JButton[] button = new JButton[MAX];
        JPanel panel = new JPanel(new GridLayout(rows, columns));
        long before = System.currentTimeMillis();
        String imageFormat = "";
        // Load all the buttons with the default pic Icon first
        for (int i = 0; i < MAX; i++) {
            if (picIcon != null) {
                button[i] = new JButton(picIcon);
            } else {
                button[i] = new JButton(name[i]);
            }
            imageFormat = name[i];
            imageFormat = imageFormat.substring(imageFormat.lastIndexOf(".") + 1);
            button[i].setPreferredSize(new Dimension(iconWidth, iconHeight));
            if (imageFormat.startsWith("j") || imageFormat.startsWith("J")) {
                imageFormat = "JPEG - JIFF Format";
            } else if (imageFormat.startsWith("p")) {
                imageFormat = "Portable Network Graphics";
            } else if (imageFormat.startsWith("bmp")) {
                imageFormat = "Bit Map Picture";
            } else if (imageFormat.startsWith("gif")) {
                imageFormat = "Graphics Interchange Format";
            } else {
                imageFormat = imageFormat.toUpperCase() + " Image Format";
            }
            // Set the button multiline tooltip
            button[i].setToolTipText("<html>" + name[i] + "<br> " + imageFormat + " </html>");
            //Add the buttons to the Panel
            panel.add(button[i]);
            panel.validate();
        }
        add(new JScrollPane(panel), BorderLayout.CENTER);
        add(statusBar, BorderLayout.SOUTH);
        //Set the Frame's properties
        setSize((iconWidth * columns) + iconWidth + 90, scrDim.height);
        setTitle("ThumbnailButtons");
        setVisible(true);
        validate();
        Image image;
        out.println("Fetching the Images, Please wait...");
        // Now update the Image preview to all the buttons
        try {
            for (int i = 0; i < MAX; i++) {
                image = getImage(path + name[i]);
                // Update the Button's icon with the preview Image
                button[i].setIcon(new ThumbnailIcon(image));
                button[i].setText("");
                // Update the button state
                button[i].validate();
                // Make the button visible by scrolling if it's not already
                button[i].scrollRectToVisible(new Rectangle(iconWidth, iconHeight));
            }
        } catch (OutOfMemoryError ome) {
            JOptionPane.showMessageDialog(null, "Oops, the JVM is running short of Heap memory!!", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(-1);
        }

        long after = System.currentTimeMillis();
        double time = (after - before) / 1000;
        statusBar.setText("Total time taken in seconds : " + time);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    // Faster way of loading Images
    public Image getImage(String fileName) {
        if (fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("png")) {
            return new ImageIcon(fileName).getImage();
        }
        try {
            return ImageIO.read(new File(fileName));
        } catch (IOException ioe) {
            System.err.println("Error loading Image!!");
        }
        return null;
    }

    /**
     *  [MENTION=9956]PARAM[/MENTION] args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Thread(new ThumbnailButtons()).start();
            }
        });
    }

    // To show a preview Image icon
    private class ThumbnailIcon implements Icon {

        private final int MAX_WIDTH = 120;
        private final int MAX_HEIGHT = 90;
        private Image thumb = null;
        private int height, width;
        private double aspect;

        public ThumbnailIcon(Image image) {
            if (image != null) {
                thumb = image;
                height = thumb.getHeight(null);
                width = thumb.getWidth(null);
                aspect = ((double) width / (double) height);
            }
        }

        @Override
        public int getIconHeight() {
            return MAX_HEIGHT;
        }

        @Override
        public int getIconWidth() {
            return MAX_WIDTH;
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2d = (Graphics2D) g;
            // Set RenderingHints properties - Speed
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            width = getWidth();
            height = getHeight();
            int topBorder = (MAX_HEIGHT - height) / 2;
            int leftBorder = (MAX_WIDTH - width) / 2;
            if (thumb != null) {
                // Scale the Image on the fly
                g2d.drawImage(thumb, 10, 10, getIconWidth(), getIconHeight(), c);
            }
        }
    }
}
```

*s4.postimg.org/s1dhds821/Thumbnail_Buttons.jpg

*JProgressBar*

Sometimes a task running within a program might take a while to complete. A user-friendly program provides some indication to the user that the task is occurring,
how long the task might take, and how much work has already been done. One way of indicating work, and perhaps the amount of progress, is to use an animated image.
Sometimes you can't immediately determine the length of a long-running task, or the task might stay stuck at the same state of completion for a long time. You can show work 
without measurable progress by putting the progress bar in indeterminate mode. A progress bar in indeterminate mode displays animation to indicate that work is occurring. 
As soon as the progress bar can display more meaningful information, you should switch it back into its default, determinate mode.

The following demo shows the Images loading progress using a ProgressBar.

ProgressBarDemo.java


```
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

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

    private String path = "Images/";
    private JLabel label = new JLabel();
    private JProgressBar progressBar = new JProgressBar(0, 100);
    private String []imgName;
    private JPanel bottom = new JPanel();
    private Thread thread = null;
    private int MAX;

    public ProgressBarDemo() {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }  catch (Exception e) {
            // Do nothing
        }
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);
        progressBar.updateUI();
        progressBar.setPreferredSize(new Dimension(250, 32));
        //Filter out the Images
        File directory = new File(path);
        if(!directory.exists()) {
            System.out.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        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;
            }
        });
        MAX = imgName.length;
        if(MAX == 0) {
            System.out.println("No Images found!!! , Exiting!!!");
            System.exit(-1);
        }
        else
        {
            bottom.setLayout(new FlowLayout(FlowLayout.CENTER));
            bottom.add(new JLabel("Loading Images, Please wait..."));
            bottom.add(progressBar);

            add(label, BorderLayout.CENTER);

            add(bottom, BorderLayout.SOUTH);
            setSize(Toolkit.getDefaultToolkit().getScreenSize());
            setTitle("ProgressBarDemo");
            setVisible(true);
            start();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }

    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 void loadImages() {
        int count = 0;
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        for (int i = 0; i < MAX; i++) {
            count =  (i*100)/(MAX -1);
            progressBar.setValue(count);
            label.setIcon(new ImageIcon(getImage(path + imgName[i])));
        }
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        remove(bottom);
        validate();
    }

    public void start() {
        if(thread == null) {
            thread = new Thread(this);
            thread.setPriority(Thread.MAX_PRIORITY);
            thread.start();
        }
    }

    @Override
    public void run() {
        loadImages();
    }

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

*s30.postimg.org/mx921mofx/Progress_Bar_Demo.jpg

*ProgressMonitor*

Now let's rewrite ProgressBarDemo to use a progress monitor instead of a progress bar.
By default, a progress monitor waits a minium of 500 milliseconds before deciding whether to pop up the dialog.
It also waits for the progress to become more than the minimum value. If it calculates that the task will take more 
than 2000 milliseconds to complete, the progress dialog appears. To adjust the minimum waiting period, invoke setMillisToDecidedToPopup.
To adjust the minimum progress time required for a dialog to appear, invoke setMillisToPopup.


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/24/14
 * Time: 2:34 PM
 * To change this template use File | Settings | File Templates.
 */
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

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

    private String path = "Images/";
    private JLabel label = new JLabel();
    private ProgressMonitor progressMonitor = new ProgressMonitor(null, "Loading Images, Please wait...", "", 0, 100);
    private String []imgName;
    private Thread thread = null;
    private int MAX;

    public ProgressMonitorDemo() {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }  catch (Exception e) {
            // Do nothing
        }
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);

        //Filter out the Images
        File directory = new File(path);
        if(!directory.exists()) {
            System.out.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        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;
            }
        });
        MAX = imgName.length;
        if(MAX == 0) {
            System.out.println("No Images found!!! , Exiting!!!");
            System.exit(-1);
        }
        else
        {
            add(label, BorderLayout.CENTER);
            setSize(Toolkit.getDefaultToolkit().getScreenSize());
            setTitle("ProgressMonitorDemo");
            setVisible(true);
            start();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }

    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 void loadImages() {
        int count = 0;
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        for (int i = 0; i < MAX; i++) {
            count =  (i*100)/(MAX -1);
            progressMonitor.setProgress(count);
            progressMonitor.setNote("" + count + "% done");
            //Display the Image
            label.setIcon(new ImageIcon(getImage(path + imgName[i])));
        }
        //Beep!!
        Toolkit.getDefaultToolkit().beep();
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }

    public void start() {
        if(thread == null) {
            thread = new Thread(this);
            thread.setPriority(Thread.MAX_PRIORITY);
            thread.start();
        }
    }

    @Override
    public void run() {
        loadImages();
    }

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

*s14.postimg.org/irdh81s31/Progress_Monitor_Demo.jpg

*JSlider*

A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value. 
If space is limited, a spinner is a possible alternative to a slider.
By default, spacing for major and minor tick marks is zero. To see tick marks, you must explicitly set the spacing 
for either major or minor tick marks (or both) to a non-zero value and call the setPaintTicks(true) method. However,
you also need labels for your tick marks. To display standard, numeric labels at major tick mark locations, set the 
major tick spacing, then call the setPaintLabels(true) method.
When you move the slider's knob, the stateChanged method of the slider's ChangeListener is called.

In the following demo we use a Slider to rotate an Image clockwise!!.


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 8/2/14
 * Time: 2:15 PM
 * To change this template use File | Settings | File Templates.
 */

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Sowndar
 */
public class SliderDemo extends JPanel {

    private BufferedImage buffImage;
    private String path = "Images/";
    private Font font = new Font("Serif", Font.BOLD, 20);
    private int imgWidth, imgHeight;
    private JSlider slider;
    private int value = 0;
    private static JPanel bottom;
    private final Dimension scrDim;
    private String fileName;
    private String []imgName;
    private int MAX;

    public SliderDemo() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            System.err.println("Error loading System look'n feel!!");
        }
        File directory = new File(path);
        if(!directory.exists()) {
            System.err.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        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;
            }
        });
        MAX = imgName.length;
        if(MAX == 0) {
            System.err.println("OOps, No Images found!!");
            System.exit(-1);
        }
        bottom = new JPanel(new FlowLayout(FlowLayout.CENTER));
        int rand = (int) (MAX * Math.random());
        buffImage = getImage(path + imgName[rand]);
        slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
        slider.setMajorTickSpacing(25);
        slider.setMinorTickSpacing(5);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setPreferredSize(new Dimension(450, 45));
        slider.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                value = slider.getValue();
                repaint();
            }
        });

        bottom.add(new JLabel("Degrees : "));
        bottom.add(slider);
        setBackground(Color.green.darker());

        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        if (buffImage != null) {
            imgWidth = buffImage.getWidth();
            imgHeight = buffImage.getHeight();
            // Resize bigger Images
            if (imgWidth > scrDim.width / 2 || imgHeight > scrDim.height) {

                buffImage = toBufferedImage(resizeImage(buffImage));
            }
        } else {
            System.exit(-1);
        }
        setPreferredSize(new Dimension(imgWidth + 450, scrDim.height - 100));
    }

    public Image resizeImage(Image image) {
        if (image != null) {

            double aspect = ((double) imgWidth) / ((double) imgHeight);
            int maxWidth, maxHeight;
            // If aspect ratio exceeds 1.3333
            if (aspect > 1.3333) {
                // Fix the width as maxWidth, calculate the maxHeight
                maxWidth = scrDim.width / 2;
                maxHeight = (int) (((double) maxWidth) / aspect);
            } else {
                // Fix the height as iconHeight, calculate the maxWidth for this
                maxHeight = scrDim.height - 50;
                maxWidth = (int) (((double) maxHeight) * aspect);
            }
            imgWidth = maxWidth;
            imgHeight = maxHeight;
            return image.getScaledInstance(maxWidth, maxHeight, Image.SCALE_SMOOTH);
        }
        return null;
    }

    public BufferedImage toBufferedImage(Image image) {
        if (image != null) {
            BufferedImage buff = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = buff.createGraphics();
            g2.drawImage(image, 0, 0, null);
            g2.dispose();
            return buff;
        }
        return null;
    }

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

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        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);

        g2d.setFont(font);
        g2d.setColor(Color.black);

        AffineTransform tx = new AffineTransform();
        // Set the angle to rotate
        // + degrees means clockwise, - degrees means anti-clockwise
        tx.rotate(Math.toRadians(value), imgWidth / 2, imgHeight / 2);

        AffineTransformOp transformOp = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
        // Transforms the source BufferedImage
        // Center the Image on the screen
        int X = (getWidth() - imgWidth) / 2;
        int Y = (getHeight() - imgHeight) / 2;

        // Draw the transformed Image
        g2d.drawImage(transformOp.filter(buffImage, null), X, Y, this);
        g2d.setColor(Color.yellow);
        g2d.drawString("Rotate : " + value + " degrees", 15, 15);
    }

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

            @Override
            public void run() {
                JFrame frame = new JFrame("SliderDemo");
                frame.add(new SliderDemo());
                frame.add(bottom, BorderLayout.SOUTH);
                frame.pack();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

*s1.postimg.org/bfs7xtdjv/Slider_Demo.jpg

*JSplitPane*

A JSplitPane displays two components, either side by side or one on top of the other. By dragging the divider that
appears between the components, the user can specify how much of the split pane's total area goes to each component.
You can divide screen space among three or more components by putting split panes inside of split panes.

In the following demo we load two random Images & show them using a SplitPane.
By the way, the splitpane can also be nested!!


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 8/2/14
 * Time: 2:23 PM
 * To change this template use File | Settings | File Templates.
 */
// Split Pane demo

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

class SplitPaneDemo extends JFrame {

    private JSplitPane splitPane = null;
    private JLabel label1 = null;
    private JLabel label2 = null;
    private Dimension scrDim;
    private String path = "Images/";
    private String []imgName;
    private int MAX;

    // SplitPane Constructor
    SplitPaneDemo(String fName) {
        super(fName);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) {
            System.err.println("Error loading System look'n feel!!");
        }
        File directory = new File(path);
        if(!directory.exists()) {
            System.out.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;
            }
        });
        MAX = imgName.length;
        if(MAX == 0) {
            System.out.println("No Images found!!! , Exiting!!!");
            System.exit(-1);
        }

        label1 = new JLabel();
        //Get a random number
        int rand = getRandom();
        label1.setIcon(new ImageIcon(getImage(path + imgName[rand])));
        label1.setMinimumSize(new Dimension(20, 20));

        label2 = new JLabel();
        int rand2 = getRandom();
        if(rand2 == rand) {
            rand2 = getRandom();
        }
        label2.setIcon(new ImageIcon(getImage(path + imgName[rand2])));
        label2.setMinimumSize(new Dimension(20, 20));

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, label1, label2);
        splitPane.setContinuousLayout(true);
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(1);
        splitPane.setDividerSize(7);
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        splitPane.setDividerLocation(scrDim.width / 2);

        add(splitPane, BorderLayout.CENTER);
        setBackground(Color.black);
        add(createSplitPaneControls(), BorderLayout.SOUTH);
        setSize(Toolkit.getDefaultToolkit().getScreenSize());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

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

    public int getRandom() {
        return (int) (MAX * Math.random());
    }

    // Creates controls to alter the JSplitPane.
    protected JPanel createSplitPaneControls() {
        JPanel wrapper = new JPanel();
        ButtonGroup group = new ButtonGroup();
        JRadioButton button;
        Box buttonWrapper = new Box(BoxLayout.X_AXIS);
        wrapper.setLayout(new GridLayout(0, 1));
        wrapper.setBorder(new EtchedBorder());

        // Create a radio button to vertically split the split pane.
        button = new JRadioButton("Vertically Split");
        button.setMnemonic('V');
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
                splitPane.setDividerLocation(scrDim.height / 2);
            }
        });
        group.add(button);
        buttonWrapper.add(button);

        // Create a radio button the horizontally split the split pane.
        button = new JRadioButton("Horizontally Split");
        button.setMnemonic('H');
        button.setSelected(true);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
                splitPane.setDividerLocation(scrDim.width / 2);
            }
        });
        group.add(button);
        buttonWrapper.add(button);

        // Create a check box as to whether or not the split pane continually lays out the component when dragging.
        JCheckBox checkBox = new JCheckBox("Continous Layout");
        checkBox.setMnemonic('C');
        checkBox.setSelected(true);

        checkBox.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                splitPane.setContinuousLayout(
                        ((JCheckBox) e.getSource()).isSelected());
            }
        });
        buttonWrapper.add(checkBox);

        // Create a check box as to whether or not the split pane divider contains the oneTouchExpandable buttons.
        checkBox = new JCheckBox("One-Touch expandable");
        checkBox.setMnemonic('O');
        checkBox.setSelected(true);

        checkBox.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                splitPane.setOneTouchExpandable(
                        ((JCheckBox) e.getSource()).isSelected());
            }
        });
        buttonWrapper.add(checkBox);
        wrapper.add(buttonWrapper);
        return wrapper;
    }

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

            @Override
            public void run() {
                new SplitPaneDemo("SplitPaneDemo");
            }
        });
    }
}
```

*s27.postimg.org/xezguao4f/Split_Pane_Demo.jpg

*JTabbedPane*

With the JTabbedPane class, you can have several components, such as panels, share the same space. The user chooses which 
component to view by selecting the tab corresponding to the desired component. If you want similar functionality without the 
tab interface, you can use a card layout instead of a tabbed pane.

In this demo we load the Images, show them in tabs, also we show the animated Images moving in different directions.


```
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Random;

/**
 * JTabbedPane Demo
 *
 * @version 1.11 11/17/05
 * @author JGuru
 */
public class TabbedPaneDemo extends JPanel implements ActionListener {

    private final HeadSpin spin;
    private final JTabbedPane tabbedpane;
    private final ButtonGroup group;
    private final JRadioButton top;
    private final JRadioButton bottom;
    private final JRadioButton left;
    private final JRadioButton right;
    private static Dimension scrDim;
    private int maxWidth, maxHeight;
    private int MAX;
    private String path = "Images/";
    private String[] imgName;
    private ImageIcon[] icon;

    /**
     * TabbedPaneDemo Constructor
     */
    public TabbedPaneDemo() {

        File directory = new File(path);
        if(!directory.exists()) {
            System.err.println("The specified directory doesn't exist!!");
            System.exit(-1);
        }
        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
        }
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        imgName = new File(path).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;
            }
        });
        MAX = imgName.length;

        if(MAX == 0) {
            System.err.println("Sorry , No Images found!!");
            System.exit(-1);
        }
        //Limit the maximum Images to 14
        if(MAX > 14) {
            MAX = 14;
        }
        setLayout(new BorderLayout());
        // create tab position controls
        JPanel tabControls = new JPanel();
        tabControls.add(new JLabel("Tab Placement"));
        top = (JRadioButton) tabControls.add(new JRadioButton("Top"));
        left = (JRadioButton) tabControls.add(new JRadioButton("Left"));
        bottom = (JRadioButton) tabControls.add(new JRadioButton("Bottom"));
        right = (JRadioButton) tabControls.add(new JRadioButton("Right"));
        add(tabControls, BorderLayout.NORTH);

        group = new ButtonGroup();
        group.add(top);
        group.add(bottom);
        group.add(left);
        group.add(right);

        top.setSelected(true);

        top.addActionListener(this);
        bottom.addActionListener(this);
        left.addActionListener(this);
        right.addActionListener(this);

        // create tab
        tabbedpane = new JTabbedPane();
        add(tabbedpane, BorderLayout.CENTER);

        String name = "";

        JLabel pix;
        icon = new ImageIcon[MAX];
        String tooltip = "";
        // Load all the Images
        for (int i = 0; i < MAX; i++) {
            name = imgName[i];
            icon[i] = createImageIcon(path + name, name);
            pix = new JLabel(icon[i]);
            tooltip = name.substring(name.lastIndexOf(".")+1).toUpperCase() + " Image";
            tabbedpane.addTab(name.substring(0, name.lastIndexOf(".")), getIcon(icon[i]), new JScrollPane(pix), tooltip);
        }
        name = "<html><font color=blue><bold><center>Bouncing Images!</center></bold></font></html>";
        spin = new HeadSpin();
        tabbedpane.add(name, spin);

        tabbedpane.getModel().addChangeListener(
                new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent e) {
                        SingleSelectionModel model = (SingleSelectionModel) e.getSource();
                        if (model.getSelectedIndex() == tabbedpane.getTabCount() - 1) {
                            spin.go();
                        }
                    }
                }
        );
    }

    public ImageIcon getIcon(ImageIcon icon) {

        if (icon != null) {
            return new ImageIcon(icon.getImage().getScaledInstance(32, 32, Image.SCALE_SMOOTH));
        }
        return null;
    }

    public ImageIcon createImageIcon(String filename, String description) {
        if (filename.endsWith("jpg") || filename.endsWith("png")) {
            return new ImageIcon(filename, description);
        }
        try {
            return new ImageIcon(ImageIO.read(new File(filename)));
        } catch (IOException ioe) {
        }
        return null;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == top) {
            tabbedpane.setTabPlacement(JTabbedPane.TOP);
        } else if (source == left) {
            tabbedpane.setTabPlacement(JTabbedPane.LEFT);
        } else if (source == bottom) {
            tabbedpane.setTabPlacement(JTabbedPane.BOTTOM);
        } else if (source == right) {
            tabbedpane.setTabPlacement(JTabbedPane.RIGHT);
        }
    }

    private class HeadSpin extends JComponent implements ActionListener {

        private Timer animator;
        private final int numImages = MAX;
        private final double[] x = new double[numImages];
        private final double[] y = new double[numImages];
        private final int[] xh = new int[numImages];
        private final int[] yh = new int[numImages];
        private final double[] scale = new double[numImages];
        private final Random rand = new Random();

        public HeadSpin() {
            setBackground(Color.black);
        }

        public void go() {
            animator = new Timer(22 + 22 + 22, this);
            animator.start();
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());

            for (int i = 0; i < numImages; i++) {
                if (x[i] > 3 * i) {
                    nudge(i);
                    squish(g, icon[i], xh[i], yh[i], scale[i]);
                } else {
                    x[i] += .05;
                    y[i] += .05;
                }
            }
        }

        public void nudge(int i) {
            x[i] += (double) rand.nextInt(1000) / 8756;
            y[i] += (double) rand.nextInt(1000) / 5432;
            int tmpScale = (int) (Math.abs(Math.sin(x[i])) * 10);
            scale[i] = (double) tmpScale / 10;
            int nudgeX = (int) (((double) getWidth() / 2) * .8);
            int nudgeY = (int) (((double) getHeight() / 2) * .60);
            xh[i] = (int) (Math.sin(x[i]) * nudgeX) + nudgeX;
            yh[i] = (int) (Math.sin(y[i]) * nudgeY) + nudgeY;
        }

        public void squish(Graphics g, ImageIcon icon, int x, int y, double scale) {
            if (isVisible()) {
                g.drawImage(icon.getImage(), x, y,
                        (int) (icon.getIconWidth() * scale),
                        (int) (icon.getIconHeight() * scale),
                        this);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (isVisible()) {
                repaint();
            } else {
                animator.stop();
            }
        }
    }

    /**
     * main method allows us to run as a standalone demo.
     *
     *  [MENTION=9956]PARAM[/MENTION] args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("TabbedPaneDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TabbedPaneDemo());
                frame.setSize(new Dimension(scrDim.width / 2 + 190, scrDim.height));
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
```

*s23.postimg.org/5kli49p13/Tabbed_Pane_Demo.jpg

See *Java Swing : The Ultimate Guide* link : *www.digit.in/forum/programming/187236-java-swing-ultimate-guide.html

Q) What is double buffering?

Ans. Suppose you had to draw an entire picture on the screen, pixel by pixel or line by line. If you were to draw such a thing 
directly to the screen (using, say, Graphics.drawLine), you would probably notice with much disappointment that it takes a bit
of time. You will probably even notice visible artifacts of how your picture is drawn. Rather than watching things being drawn 
in this fashion and at this pace, most programmers use a technique called double-buffering.

The traditional notion of double-buffering in Java applications is fairly straightforward: create an offscreen image, draw to 
that image using the image's graphics object, then, in one step, call drawImage using the target window's graphics object and
the offscreen image. You may have already noticed that Swing uses this technique in many of its components, usually enabled 
by default, using the setDoubleBuffered method.

Double-buffering is used primarily to eliminate visible draws which can make an application look amateurish, sluggish, or 
appear to flicker. Page-flipping is used primarily to also eliminate tearing, a splitting effect that occurs when drawing
to the screen happens faster than the monitor's refresh rate. Smoother drawing means better perceived performance and a much
better user experience.


```
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/*
 * This app animates graphics that it generates.  This example
 * eliminates flashing by double buffering.
 */
public class DoubleBuffer extends JPanel implements Runnable {

    private int frameNumber = -1;
    private Thread animatorThread;
    private boolean frozen = false;
    private int squareSize = 40;
    private boolean fillColumnTop = true;
    private Dimension offDimension;
    private Image offImage;
    private Graphics offGraphics;
    private int fps = 10;

    public DoubleBuffer() {
        Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(scrDim.width / 2 + 100, scrDim.height / 2 + 100));
    }

    public void start() {
        if (frozen) {
            //Do nothing.  The user has requested that we
            //stop changing the image.
        } else {
            //Start animating!
            if (animatorThread == null) {
                animatorThread = new Thread(this);
            }
            animatorThread.start();
        }
    }

    public void stop() {
        //Stop the animating thread.
        animatorThread = null;

        //Get rid of the objects necessary for double buffering.
        offGraphics = null;
        offImage = null;
    }

    public void mousePressed(MouseEvent me) {
        if (frozen) {
            frozen = false;
            start();
        } else {
            frozen = true;

            //Instead of calling stop(), which destroys the
            //backbuffer, just stop the animating thread.
            animatorThread = null;
        }
        //return true;
    }

    @Override
    public void run() {
        //Just to be nice, lower this thread's priority
        //so it can't interfere with other processing going on.
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        //This is the animation loop.
        while (Thread.currentThread() == animatorThread) {
            //Advance the animation frame.
            frameNumber++;

            //Display it.
            repaint();
            // Delay for a moment
            try {

                Thread.sleep(5);
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        update(g);
    }

    @Override
    public void update(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        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);

        Dimension d = getSize();
        boolean fillSquare;
        boolean fillNextFrame;
        int rowWidth = 0;
        int x = 0, y = 0;
        int w, h;
        int tmp;

        //Create the offscreen graphics context, if no good one exists.
        if ((offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height)) {
            offDimension = d;
            offImage = createImage(d.width, d.height);
            offGraphics = offImage.getGraphics();
        }

        //Erase the previous image.
        offGraphics.setColor(getBackground());
        offGraphics.fillRect(0, 0, d.width, d.height);
        offGraphics.setColor(Color.black);

        //Set width of first "square". Decide whether to fill it.
        fillSquare = fillColumnTop;
        fillColumnTop = !fillColumnTop;
        tmp = frameNumber % squareSize;
        if (tmp == 0) {
            w = squareSize;
            fillNextFrame = !fillSquare;
        } else {
            w = tmp;
            fillNextFrame = fillSquare;
        }

        //Draw from left to right.
        while (x < d.width) {
            int colHeight = 0;

            //Draw the column.
            while (y < d.height) {
                colHeight += squareSize;

                //If we don't have room for a full square, cut if off.
                if (colHeight > d.height) {
                    h = d.height - y;
                } else {
                    h = squareSize;
                }

                //Draw the rectangle if necessary.
                if (fillSquare) {
                    offGraphics.fillRect(x, y, w, h);
                    fillSquare = false;
                } else {
                    fillSquare = true;
                }

                y += h;
            } //while y

            //Determine x, y, and w for the next go around.
            x += w;
            y = 0;
            w = squareSize;
            rowWidth += w;
            if (rowWidth > d.width) {
                w = d.width - x;
            }
            fillSquare = fillColumnTop;
            fillColumnTop = !fillColumnTop;
        } //while x
        fillColumnTop = fillNextFrame;

        //Paint the image onto the screen.
        g2d.drawImage(offImage, 0, 0, this);
    }

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

            @Override
            public void run() {
                JFrame f = new JFrame("DoubleBuffer");
                DoubleBuffer buffer = new DoubleBuffer();
                f.add(buffer);
                f.pack();
                buffer.start();
                f.setVisible(true);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

*s10.postimg.org/697uv2jn9/Double_Buffer.jpg

Q) How can I develop classic Data-Structures like LinkedList, since Java doesn't have pointers?

Ans. Use Object reference. In Java you use a object reference to create a LinkedList. In a language like C/C++ you use a pointer.
     Object reference is much more easier to create & maintain compared with a pointer!!

 Here is a implementation for a LinkedList!!


```
class LinkedList {

    private Node head;

    public LinkedList() {
        head = null;
    }

    public boolean isEmpty() {
        return (head == null);
    }

    public void add(int data) {
        Node node = new Node(data);
        node.next = head;
        head = node;
    }

    public void remove() {
        head = head.next;
    }

    /**
     * Returns a String representation of the list.
     */
    public void display() {
        Node currentNode = head;
        while (currentNode != null) {

            System.out.println(currentNode.toString());
            currentNode = currentNode.next;
        }
    }

    /**
     * Represents a node in a linked list.
     */
    private class Node {

        public int data;
        public Node next;

        public Node(int data) {
            this.data = data;
        }

        public String toString() {
            return "(" + data + ")";
        }
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(8);
        list.add(6);
        list.add(5);
        list.add(3);
        list.remove();
        list.display();
    }
}
```
 
Q) Can I develop an application that works both as an applet & application?

Ans. Yes you can but with some limitations!!
     Applications can access any resources (locally, Internet)
     Applets can't read/write File (Sandbox) Signed Applets can circumvent this shortcoming.
     Also an applet can't connect to any arbitrary resource on the Net.
     You should also provide the methods init(), start(), stop() & invoke them . Since an applet needs these methods!!


```
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.TextEvent;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;


enum DitherMethod {

    NOOP, RED, GREEN, BLUE, ALPHA, SATURATION
};


   [MENTION=139512]Sup[/MENTION]pressWarnings("serial")
public class DitherTest extends Applet implements Runnable {

    private Thread runner;
    private DitherControls XControls;
    private DitherControls YControls;
    private DitherCanvas canvas;

    public static void main(String args[]) {
        Frame f = new Frame("DitherTest");
        DitherTest ditherTest = new DitherTest();
        ditherTest.init();
        f.add("Center", ditherTest);
        f.pack();
        f.setVisible(true);
        ditherTest.start();
    }

    @Override
    public void init() {
        String xspec = null, yspec = null;
        int xvals[] = new int[2];
        int yvals[] = new int[2];

        try {
            xspec = getParameter("xaxis");
            yspec = getParameter("yaxis");
        } catch (NullPointerException ignored) {
            //only occurs if run as application
        }

        if (xspec == null) {
            xspec = "red";
        }
        if (yspec == null) {
            yspec = "blue";
        }
        DitherMethod xmethod = colorMethod(xspec, xvals);
        DitherMethod ymethod = colorMethod(yspec, yvals);

        setLayout(new BorderLayout());
        XControls = new DitherControls(this, xvals[0], xvals[1],
                xmethod, false);
        YControls = new DitherControls(this, yvals[0], yvals[1],
                ymethod, true);
        YControls.addRenderButton();
        add("North", XControls);
        add("South", YControls);
        add("Center", canvas = new DitherCanvas());
    }

    private DitherMethod colorMethod(String s, int vals[]) {
        DitherMethod method = DitherMethod.NOOP;
        if (s == null) {
            s = "";
        }
        String lower = s.toLowerCase();

        for (DitherMethod m : DitherMethod.values()) {
            if (lower.startsWith(m.toString().toLowerCase())) {
                method = m;
                lower = lower.substring(m.toString().length());
            }
        }
        if (method == DitherMethod.NOOP) {
            vals[0] = 0;
            vals[1] = 0;
            return method;
        }
        int begval = 0;
        int endval = 255;
        try {
            int dash = lower.indexOf('-');
            if (dash < 0) {
                endval = Integer.parseInt(lower);
            } else {
                begval = Integer.parseInt(lower.substring(0, dash));
                endval = Integer.parseInt(lower.substring(dash + 1));
            }
        } catch (NumberFormatException ignored) {
        }

        if (begval < 0) {
            begval = 0;
        } else if (begval > 255) {
            begval = 255;
        }

        if (endval < 0) {
            endval = 0;
        } else if (endval > 255) {
            endval = 255;
        }

        vals[0] = begval;
        vals[1] = endval;
        return method;
    }

    /**
     * Calculates and returns the image.  Halts the calculation and returns
     * null if the Applet is stopped during the calculation.
     */
    private Image calculateImage() {
        Thread me = Thread.currentThread();

        int width = canvas.getSize().width;
        int height = canvas.getSize().height;
        int xvals[] = new int[2];
        int yvals[] = new int[2];
        int xmethod = XControls.getParams(xvals);
        int ymethod = YControls.getParams(yvals);
        int pixels[] = new int[width * height];
        int c[] = new int[4];   //temporarily holds R,G,B,A information
        int index = 0;
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                c[0] = c[1] = c[2] = 0;
                c[3] = 255;
                if (xmethod < ymethod) {
                    applyMethod(c, xmethod, i, width, xvals);
                    applyMethod(c, ymethod, j, height, yvals);
                } else {
                    applyMethod(c, ymethod, j, height, yvals);
                    applyMethod(c, xmethod, i, width, xvals);
                }
                pixels[index++] = ((c[3] << 24) | (c[0] << 16) | (c[1] << 8)
                        | c[2]);
            }

            // Poll once per row to see if we've been told to stop.
            if (runner != me) {
                return null;
            }
        }
        return createImage(new MemoryImageSource(width, height,
                ColorModel.getRGBdefault(), pixels, 0, width));
    }

    private void applyMethod(int c[], int methodIndex, int step,
            int total, int vals[]) {
        DitherMethod method = DitherMethod.values()[methodIndex];
        if (method == DitherMethod.NOOP) {
            return;
        }
        int val = ((total < 2)
                ? vals[0]
                : vals[0] + ((vals[1] - vals[0]) * step / (total - 1)));
        switch (method) {
            case RED:
                c[0] = val;
                break;
            case GREEN:
                c[1] = val;
                break;
            case BLUE:
                c[2] = val;
                break;
            case ALPHA:
                c[3] = val;
                break;
            case SATURATION:
                int max = Math.max(Math.max(c[0], c[1]), c[2]);
                int min = max * (255 - val) / 255;
                if (c[0] == 0) {
                    c[0] = min;
                }
                if (c[1] == 0) {
                    c[1] = min;
                }
                if (c[2] == 0) {
                    c[2] = min;
                }
                break;
        }
    }

    @Override
    public void start() {
        runner = new Thread(this);
        runner.start();
    }

    @Override
    public void run() {
        canvas.setImage(null);  // Wipe previous image
        Image img = calculateImage();
        if (img != null && runner == Thread.currentThread()) {
            canvas.setImage(img);
        }
    }

    @Override
    public void stop() {
        runner = null;
    }

    @Override
    public void destroy() {
        remove(XControls);
        remove(YControls);
        remove(canvas);
    }

    @Override
    public String getAppletInfo() {
        return "An interactive demonstration of dithering.";
    }

    @Override
    public String[][] getParameterInfo() {
        String[][] info = {
            { "xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
                "The color of the Y axis.  Default is RED." },
            { "yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
                "The color of the X axis.  Default is BLUE." }
        };
        return info;
    }
}


   [MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class DitherCanvas extends Canvas {

    private Image img;
    private static String calcString = "Calculating...";

    @Override
    public void paint(Graphics g) {
        int w = getSize().width;
        int h = getSize().height;
        if (img == null) {
            super.paint(g);
            g.setColor(Color.black);
            FontMetrics fm = g.getFontMetrics();
            int x = (w - fm.stringWidth(calcString)) / 2;
            int y = h / 2;
            g.drawString(calcString, x, y);
        } else {
            g.drawImage(img, 0, 0, w, h, this);
        }
    }

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

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(20, 20);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    public Image getImage() {
        return img;
    }

    public void setImage(Image img) {
        this.img = img;
        repaint();
    }
}


   [MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class DitherControls extends Panel implements ActionListener {

    private CardinalTextField start;
    private CardinalTextField end;
    private Button button;
    private Choice choice;
    private DitherTest applet;
    private static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER,
            10, 5);

    public DitherControls(DitherTest app, int s, int e, DitherMethod type,
            boolean vertical) {
        applet = app;
        setLayout(dcLayout);
        add(new Label(vertical ? "Vertical" : "Horizontal"));
        add(choice = new Choice());
        for (DitherMethod m : DitherMethod.values()) {
            choice.addItem(m.toString().substring(0, 1)
                    + m.toString().substring(1).toLowerCase());
        }
        choice.select(type.ordinal());
        add(start = new CardinalTextField(Integer.toString(s), 4));
        add(end = new CardinalTextField(Integer.toString(e), 4));
    }

    /* puts on the button */
    public void addRenderButton() {
        add(button = new Button("New Image"));
        button.addActionListener(this);
    }

    /* retrieves data from the user input fields */
    public int getParams(int vals[]) {
        try {
            vals[0] = scale(Integer.parseInt(start.getText()));
        } catch (NumberFormatException nfe) {
            vals[0] = 0;
        }
        try {
            vals[1] = scale(Integer.parseInt(end.getText()));
        } catch (NumberFormatException nfe) {
            vals[1] = 255;
        }
        return choice.getSelectedIndex();
    }

    /* fits the number between 0 and 255 inclusive */
    private int scale(int number) {
        if (number < 0) {
            number = 0;
        } else if (number > 255) {
            number = 255;
        }
        return number;
    }

    /* called when user clicks the button */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button) {
            applet.start();
        }
    }
}


   [MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class CardinalTextField extends TextField {

    String oldText = null;

    public CardinalTextField(String text, int columns) {
        super(text, columns);
        enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.TEXT_EVENT_MASK);
        oldText = getText();
    }

    // Consume non-digit KeyTyped events
    // Note that processTextEvent kind of eliminates the need for this
    // function, but this is neater, since ideally, it would prevent
    // the text from appearing at all.  Sigh.  See bugid 4100317/4114565.
    //
    @Override
    protected void processEvent(AWTEvent evt) {
        int id = evt.getID();
        if (id != KeyEvent.KEY_TYPED) {
            super.processEvent(evt);
            return;
        }

        KeyEvent kevt = (KeyEvent) evt;
        char c = kevt.getKeyChar();

        // Digits, backspace, and delete are okay
        // Note that the minus sign is not allowed (neither is decimal)
        if (Character.isDigit(c) || (c == '\b') || (c == '\u007f')) {
            super.processEvent(evt);
            return;
        }

        Toolkit.getDefaultToolkit().beep();
        kevt.consume();
    }

    // Should consume TextEvents for non-integer Strings
    // Store away the text in the tf for every TextEvent
    // so we can revert to it on a TextEvent (paste, or
    // legal key in the wrong location) with bad text
    //
    // Note: it would be easy to extend this to an eight-bit
    // TextField (range 0-255), but I'll leave it as-is.
    //
    @Override
    protected void processTextEvent(TextEvent te) {
        // The empty string is okay, too
        String newText = getText();
        if (newText.equals("") || textIsCardinal(newText)) {
            oldText = newText;
            super.processTextEvent(te);
            return;
        }

        Toolkit.getDefaultToolkit().beep();
        setText(oldText);
    }

    // Returns true for Cardinal (non-negative) numbers
    // Note that the empty string is not allowed
    private boolean textIsCardinal(String textToCheck) {
        try {
            return Integer.parseInt(textToCheck, 10) >= 0;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }
}
```

*s28.postimg.org/rvk5rmtkp/Dither_Test.jpg

Q) How do I map an area in the Image ?

Ans. You can map different areas in the Image for different things. For eg., if you click a certain area of the Image, you
can load a web page, play some sound etc.,

The following program highlights the regions - left eye, right eye, nose, mouth . When you move the Mouse pointer over the
specific region.

We use a MouseMotionListener to achieve this.


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 12/1/14
 * Time: 1:50 PM
 * To change this template use File | Settings | File Templates.
 */

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.File;
import java.io.IOException;

// Left eye - 494 , 205 124 , 109
// Right eye - 656 , 216 134 , 112
// Nose - 610 , 295 52 , 121
// Mouth - 560 , 429 133 , 67

public class ImageMapDemo extends JPanel {

    private int x, y;
    private Dimension scrDim;
    private int red = 0, green = 124, blue = 0, alpha = 80;
    private Color green2 = new Color(red, green, blue, alpha);
    private Image image;
    // Mapping the area within the Image
    // Left Eye
    int leftEyeX = 494;
    int leftEyeY = 205;
    int leftEyeWidth = 124;
    int leftEyeHeight = 109;
    // Right Eye
    int rightEyeX = 656;
    int rightEyeY = 216;
    int rightEyeWidth = 134;
    int rightEyeHeight = 112;
    // Nose
    int noseX = 610;
    int noseY = 295;
    int noseWidth = 52;
    int noseHeight = 121;
    // Mouth
    int mouthX = 560;
    int mouthY = 429;
    int mouthWidth = 133;
    int mouthHeight = 67;
    int mx, my;
    int X, Y;
    String message = "";
    int width, height;

    public ImageMapDemo() {
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();

        image = getImage("Images/Megan Fox1.jpg");

        // Add a Mouse listener
        addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent me) {

                repaint();
            }

            @Override
            public void mouseReleased(MouseEvent me) {

                repaint();
            }
        });
        // Add a Mouse motion listener
        addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseMoved(MouseEvent me) {
                X = me.getX();
                Y = me.getY();

                //Region within the square!
                // Mouse X, Y coordinates correction
                if ((X >= leftEyeX && X <= (leftEyeX + leftEyeWidth)) && (Y >= leftEyeY && Y <= (leftEyeY + leftEyeHeight))) {

                    mx = leftEyeX;
                    my = leftEyeY;
                    width = leftEyeWidth;
                    height = leftEyeHeight;
                    message = "Left Eye";
                    repaint();
                } else if ((X >= rightEyeX && X <= (rightEyeX + rightEyeWidth)) && (Y >= rightEyeY && Y <= (rightEyeY + rightEyeHeight))) {

                    mx = rightEyeX;
                    my = rightEyeY;
                    width = rightEyeWidth;
                    height = rightEyeHeight;
                    message = "Right Eye";
                    repaint();
                } else if ((X >= noseX && X <= (noseX + noseWidth)) && (Y >= noseY && Y <= (noseY + noseHeight))) {

                    mx = noseX;
                    my = noseY;
                    width = noseWidth;
                    height = noseHeight;
                    message = "Nose";
                    repaint();
                } else if ((X >= mouthX && X <= (mouthX + mouthWidth)) && (Y >= mouthY && Y <= (mouthY + mouthHeight))) {

                    mx = mouthX;
                    my = mouthY;
                    width = mouthWidth;
                    height = mouthHeight;
                    message = "Mouth";
                    repaint();
                }
            }
        });

        setPreferredSize(scrDim);
    }

    /**
     * Overridden to return true which means that children may not overlap.
     * <p>
     * This is a little bit obscure.
     *
     * @return
     */
    @Override
    public boolean isOptimizedDrawingEnabled() {
        return true;
    }

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

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        // Set Rendering hints properties render for Speed
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        // Set the thickness of the Rectangle
        g2.setStroke(new BasicStroke(3f));
        g2.setFont(new Font("Serif", Font.BOLD, 28));

        if(image != null) {
            g2.drawImage(image, 0, 0, this);
        }
        // Draw the Highlight region
        drawHighlight(g2);
        drawString(g2);
        // Disposes of this graphics context and releases any system resources
        g2.dispose();
    }

    public void drawHighlight(Graphics2D g2d) {
        // Fill a translucent Rectangle
        float alpha = 0.8f;
        g2d.setColor(new Color(30, 80, 230, (int) (alpha * 100)));
        g2d.fillRect(mx, my, width, height);
        // Draw a rectangle outline in black color
        g2d.setColor(Color.black);
        g2d.drawRect(mx, my, width, height);
    }

    public void drawString(Graphics2D g2d) {
        // Draw a message at the bottom
        g2d.setColor(Color.red);
        g2d.drawString(message, 10, scrDim.height - 100);
    }

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

            @Override
            public void run() {
                JFrame frame = new JFrame("ImageMapDemo");
                frame.add(new ImageMapDemo());
                //Set the Frame's properties
                frame.pack();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}
```

*s29.postimg.org/xwypgxzdf/Image_Map_Demo.jpg

Here is the Image used:

*s29.postimg.org/s7n2adikz/Megan_Fox1.jpg

Q) Which are the best institutes that teach Computer programming in India ?

Ans. There are institutes like Aptech, NIIT, CSC etc., that teach the basics in C/C++/C#/Java/Oracle.
     There is RCS, Bangalore which teaches Java (Very good). NIIT/Aptech/CSC teaching is very basic!!
     So NIIT/Aptech/CSC don't make the cut. Most of the NIIT & Aptech guys don't know a wee bit about
     programming, that's the bitter truth!! I'm an Aptech student myself!! So I know the inside view of things.
     I have learnt programming by myself by studying the best books on programming & writing more programs by myself.

     On a serious note there isn't any great institute that teaches Computer programming!!
     If you want to learn Networking, Security ( CCIE, CCNP, CCNA, CCSE, CISSP, CCNA, CWNA etc.,) go for
     Top Gun Technologies, Bangalore (www.topguntechnologies.com). They are best out there in Security & Networking.

     You can also study in the top colleges in India like VIT (Vellore Institute of Technology), NIT (National Institute of Technology),
     SRM University, IIIT (Indian Institute of Information Technology), BITS (Birla Institute of Technology & Science), Amity University etc.,

     Most of the top colleges have campus recruitment. The companies like TCS, Infosys, Cognizant, Oracle, Google, Honeywell, etc., recruit from the top colleges.

Q) What are the projects I can do in Java?

  Ans. You can write a GUI (Swing) application, applet or a e-commerce application (Servlet/JSP) or a JavaME (Java Micro Edition).
       Here are some projects that you can do.

*Swing (GUI)*

   1) Banking System

   2) Customer Relationship Software (CRM)

   3) Text Editor (TextPad)

   4) Integrated Development Environment (IDE like NetBeans, Eclipse, JDeveloper) (NOTE :  IDE Development is only for Java experts !!, not for novice programmers!!!)

   5) Media Player (WinAmp, iTunes)

   6) Web Browser (FireFox, Chrome, Opera)

   7) Image Processing (PhotoShop, GIMP)  *s24.postimg.org/4mg2nery9/Image_Editor.jpg

   8) Peer to Peer (P2P like LimeWire)

   9) DataBase Explorer

   10) Download Manager (FlashGet, DAP)

   11) RDBMS (Oracle, DB2, SQL Server)

   12) Supply Chain Management (SCM)

   13) Text to Speech Converter 

   14) Accounting (Tally, Busy)

   15) 3D Modelling program (using Java3D - like Blender, ZBrush, Sculptris)

   16) Geographical Information System (GIS)

   17) Enterpise Resource Planning (ERP like SAP, Oracle Financials)

   18) Compiler design in Java ( Compiler design is for Java experts , it needs professional expertise!!! It's not for novice programmers!!!)

   19) Stock Market monitoring Applet or application

   20) XML Editor

   21) Zip archiver like WinZip, WinRAR

   22) UML Editor (Unified Modeling Language)

   23) FTP Client

   24) Web Server

   25) Voice Chat & Video Conferencing (using JMF)

   26) Word processor (like MS Word )

*E-Commerce* (JSP/Servlets)

   1) Banking System

   2) HRM (Human Resource Management)

   3) Airline Reservation System

   4) Job Portal System (naukri.com, monster.com)

   5) Inventory Management System

   6) Hotel Management System

   7) Energy Billing System

   8) Travel Billing System

   9) Online ecommerce Portal (eBay, amazon.com)

   10) Telecom management System

   11) Voice chat & Video conferencing (using JMF)

*Mobile Development* (JavaME)

   1) M-commerce

   2) Game Development

   3) Media Player

   4) Web Crawler

   5) Download Manager

   6) Web Browser 


   Q) What are the books I need to study, to write a Project in Java ?

   Ans.

*Must read Books for writing Java Projects:*

   1) Core Java - Vol -I & II by Horstmann C S

   2) Beginning Java Objects (Wrox)/ Object-Oriented Programming in Java by Balagurusamy

   3) Java Tutorial 5th Edition

   4) Graphic Java 2 ,Volume 2 Swing: Mastering the JFC by David M Geary

   5) Data Structures & Algorithms in Java by Robert Lafore (Techmedia) / Algorithms in Java 4th Edition by Robert SedgeWick

   6) The Java Developers Almanac 1.4, Volume I & II by Patrick Chan

   7) Java Swing 5th Edition by Eckstein (Oreilly)

   8) Thinking in Java 

   9) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty

   10) Oracle Database JDBC Developer's Guide & Reference

   11) Beginning Java Databases / Java Database Programming Bible by John O' Donahue 

   12) Professional Java Programming (Wrox)

   13) Beginning Java Networking (Wrox)/ An Itroduction to Network Programming with Java : Java 7 Compatible by Jan Graba

   14) JSP 2.0 : The Complete Reference by Phil Hanna (Tata McGraw Hill)

   15) Struts : The Complete Reference (Tata McGraw Hill)

   16) Mastering HTML 5 (Sybex/ BPB)

   17) Professional Java Networking (Wrox)

   18) Oracle 12c: The Complete Reference (Tata McGraw Hill)

   19) Java Threads (Oreilly)

   20) Java How To Program by H M Deitel & P J Deitel 

   21) Software Engineering in Java 

   23) Desktop Java Live (Discusses various Layout Managers , GUI Builders, Swing Threading, Data Binding , Validation, Packaging & Deployment )

   24) Java Servlet Programming by Jason Hunter, William Crawford (Oreilly)

   Start writing programs from the 2nd year of college itself. Remember mastering Java Foundation Classes (JFC) takes about 6 to 8 months!!! The more programs you
   write in Java, the more comfortable you will be!!! You should code more often, read more books on Java, develop more programs using it. There are no shortcuts!!!
   You can't become expert Java programmer overnight!! Certain people use ghost-writer to write the software for them.
   This is a very bad practise!! It should be avoided at all costs!! You can get some help from a experienced programmer, in case you need some help.

   Remember the Project need not be a complex one!!! Also don't copy & paste other's Code and say that I did it!!! Guys working in a company who can't program well will be sent home!!!! 
   Be serious , work hard, success is yours. You have to work 12 hours/ day for a year to develop a good project in Java.


   Sincerely Write a Project by yourself. You'll learn lot of things in the whole process!!!   It takes hardwork, effort & application on your part to become a Software Engineer.
   There are no shortcuts!! So work hard & achieve your goal. There are some good Computer institutes that can also help you. 
   You can also download a Open Source project , learn how things are done. It's a great way to learn programming!!
   You must download the software start playing with it. See how it works. Get the nitty-gritty things right. Start writing the
   software like the one you downloaded. You can write any program like a download manager (FlashGet), Image processor (PhotoShop),
   Accounting (Tally), CRM (Seibel) etc., Apply the logic & language API to get the work done.
   I have covered a lot of topics here. The real onus is on you!! So work hard & succeed in life!!

   Goodluck!!


----------



## avinandan012 (Oct 1, 2013)

*Re: The Ultimate Guide to Java Programming &amp; Reference:*

rep + 10000^n.

Thanks for the detailed post.

@all who are considering a career in programming:

remember as op has mentioned if you know the language API half work is done the other half is formulating a best case algo+considering(minimize usage of) space time constraints(memory usage & time).

read this book
"Introduction_to_algorithms_3rd_edition.pdf" by  CORMEN
search google you will get the free version


----------



## krishnandu.sarkar (Oct 2, 2013)

Wow that's a great post above


----------



## dashing.sujay (Oct 2, 2013)

Simply great !!


----------



## deepakkrishnan (Oct 2, 2013)

Thank you


----------



## ACidBaseD (Oct 20, 2013)

wow thanks a lot! It will definetly help.
BTW Is the SCJP [For Java6] by Kathy Sierra and Bert Bates a good book to learn Concepts of Java ? [I'm in F.E Computer Engineering]


----------



## TheSloth (Jun 20, 2014)

I am going start to learn java. I do have basic programming knowledge. I was seeing the 1st post, i didn't go beyond first program.
I got doubt, in first program, there are two variables, name and ssn as String, to initialize them OP is using two methods, setName and setSsn to initialize them but he is invoking them through constructors. Isn't constructors use to initialize variables(actually objects) of classes? why OP is not initializing those two variables in constructors itself? or if he wants to initialize them via methods then why to call them in constructors? I understand that as soon as object will be declared these function would be called. But still something is there which is bothering me. Or may be I am not just used to doing things like this(callin methods in constructors to initialize).
One thing i learned while writing this post is, the correct spelling of 'initialize'. I used to use 'initialise'

One more question, i haven't learned Data structures yet. Just stack queue and all. So shall i use book mentioned in 2nd post? Or any other book?


----------



## krishnandu.sarkar (Jun 21, 2014)

lightningfassst said:


> I am going start to learn java. I do have basic programming knowledge. I was seeing the 1st post, i didn't go beyond first program.
> I got doubt, in first program, there are two variables, name and ssn as String, to initialize them OP is using two methods, setName and setSsn to initialize them but he is invoking them through constructors. Isn't constructors use to initialize variables(actually objects) of classes? why OP is not initializing those two variables in constructors itself? or if he wants to initialize them via methods then why to call them in constructors? I understand that as soon as object will be declared these function would be called. But still something is there which is bothering me. Or may be I am not just used to doing things like this(callin methods in constructors to initialize).
> One thing i learned while writing this post is, the correct spelling of 'initialize'. I used to use 'initialise'




```
//----------------
// Constructor(s).
//----------------
    public Person(String name, String ssn) {
        setName(name);
        setSsn(ssn);
    }
```

This constructor will help users to initialize the object as Person p = new Person("MyName", "999-99-9999"); i.e. at the time of creation of object using the constructor provided.


```
//-----------------
// Get/set methods.
//-----------------
    public void setName(String n) {
        name = n;
    }

    public String getName() {
        return name;
    }

    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    public String getSsn() {
        return ssn;
    }
```

Sometimes users may not want to initialize the member variables while initializing an object. So with these getters and setters, users can also initialize the member variables later, like...

Person p = new Person();

Note that we are not passing anything in the constructor. So if now we use p.getName() and p.getSsn() then what result we will get?

We'll get Name = ? and SSN = ???-??-????. Why? Constructor overloading. Person p = new Person(); is now using the 2nd constructor.

So now how can I set the values of member variables? What if we want to set it later in the program? Then we can use these getters and setters.

Person p = new Person();

And then later in the program path..

p.setName("MyName");
p.setSSN("999-99-9999");

Now if we use p.getName() and p.getSsn() we'll get MyName and 999-99-9999 respectively.

Hope that helps


----------



## TheSloth (Jun 22, 2014)

[MENTION=32490]krishnandu.sarkar[/MENTION]:Awesome . thanks for explaining with example. One lil question, the second constructor you are talking about is default constructor, right?

Very important question: I have to sit for college placements in the next two sems. So I thought of preparing JAVA. I do have Complete Reference. That would be good? What about J2EE? Shall I concentrate on core JAVA only? Also I haven't learned anything significant in Data Structures. Which book should I prefer? I am also going to prepare for Aptitude too as I am very weak in those. Another big problem is I still have lot of arrears. So I don't have time to learn everything from so many books. So it would be better that if you people suggest me only one book to read from. I can read one topic from other book and next topic from another book but can't read same topic from different books cause of less time. I hope you guys understand. 

Shall I make another thread? Sorry if I posted in wrong section


----------



## krishnandu.sarkar (Jun 22, 2014)

lightningfassst said:


> [MENTION=32490]krishnandu.sarkar[/MENTION]:Awesome . thanks for explaining with example. One lil question, the second constructor you are talking about is default constructor, right?
> 
> 
> 
> ...


----------



## TheSloth (Jun 22, 2014)

really thanks. I missed the default constructor first. I was wondering what are those ?? are. But now clear.

Also thanks for telling me about java book.
You sure about that DS book? I don't get good comments when I start talking about Indian Author books like Yashwant Kanitkar


----------



## JGuru (Aug 11, 2014)

I hope you guys like my post. I'm a veteran Java Developer myself. Hope this post helps the lakhs of fresh Graduates (BE/BTech, MCA, MSc etc.,) I posted this to serve as a help-line for those people. 

Goodluck in your quest for knowledge, & job search!!


----------



## quicky008 (Aug 19, 2014)

JGuru said:


> I hope you guys like my post. I'm a veteran Java Developer myself. Hope this post helps the lakhs of fresh Graduates (BE/BTech, MCA, MSc etc.,) I posted this to serve as a help-line for those people.
> 
> Goodluck in your quest for knowledge, & job search!!



Its a very useful post indeed-keep up the good work,venerable sir.


----------



## JGuru (Sep 5, 2014)

Most guys don't get a job because they don't know programming!!
1) Study C,C++,Java , Oracle in a good institute (1 year)
2) Study algorithms & data structures, write more programs (4 months)
3) Study these books & write a project  (6 months to 1 year)

 1) Java How To Program by H M Deitel & P J Deitel
  2) Oracle 12c: The complete Reference (Tata McGraw Hill)
  3) Core Java (2 volumes)
  4) Beginning Java Databases / Java Database Programming Bible by John O' Donahue
  5) Data Structures & Algorithms in Java by Robert Lafore (Techmedia)
  6) Algorithms (4th Edition) by Robert Sedgewick and Kevin Wayne (Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne)
  7) Big Java Late Objects by Cay S. Horstmann 
  8) Object-Oriented Programming in Java by Balagurusamy
  9) JSP 2.0 : The complete Reference by Phil Hanna
  10) Mastering HTML 5.0 (Sybex/ BPB)
  11) Struts: The complete Reference
  12) The Java FAQ by Jonni Kanerva
  13) Professional Java Programming (Wrox)
  14) Graphic Java 2, Volume 2 : Swing, Mastering the JFC by David M Geary
  15) Java Developers Almanac 1.4 (4th Edition) (2 Volumes) by Patrick Chan 
  16) Java Servlet Programming by Jason Hunter, William Crawford (Oreilly)
  17) Java Tutorial 5th Edition
  18) Effective Java by Joshua Bloch

   This will put you in a great position for a Job as a Software programmer.
   Remember you have to work hard, there are no shortcuts!!


----------



## adityak469 (Oct 21, 2014)

Hi,

I didnt read the whole thread but if you could suggest a book for class 11th java then it'll be very helpful to me. the school teachers dont teach well and the books suck.


----------



## JGuru (Nov 4, 2014)

[MENTION=129451]aditya[/MENTION], you try Head First Java by Kathy Sierra , Bert Bates(Buy Head First Java Book Online at Low Prices in India | Head First Java Reviews & Ratings - Amazon.in) . It starts from the introductory level . Good book for those new to programming.


----------



## adityak469 (Nov 7, 2014)

JGuru said:


> [MENTION=129451]aditya[/MENTION], you try Head First Java by Kathy Sierra , Bert Bates(Buy Head First Java Book Online at Low Prices in India | Head First Java Reviews & Ratings - Amazon.in) . It starts from the introductory level . Good book for those new to programming.



you linked me to a 11k book  

I'll buy the Rs 615 one. i.e this


----------



## JGuru (Nov 10, 2014)

Aditya, I gave you the Amazon link to show the book. The book is available in US & Indian edition.
You should also learn OOPS (Object oriented Programming System) & programming guide.
There are shops in Bangalore , Mumbai that sell Indian edition at discount rate (10%).

 Other books you should study are :

1) 
*Beginning Java Objects* by Jacquie Barke (Wrox) Buy Beginning Java Objects Book Online at Low Prices in India | Beginning Java Objects Reviews & Ratings - Amazon.in
2) 
*Java How to Program* by Deitel Paul (Author), Deitel Harvey Buy Java How to Program Book Online at Low Prices in India | Java How to Program Reviews & Ratings - Amazon.in


----------



## JGuru (Dec 4, 2014)

I recommend these books:

1) Core Java by Cay S. Horstmann (2 volumes) Buy Core Java Volume 1 Fundamentals Book Online at Low Prices in India | Core Java Volume 1 Fundamentals Reviews & Ratings - Amazon.in

2) The Java Faq by Kanerva Amazon.in: Buy The Java Faq Book Online at Low Prices in India | The Java Faq Reviews & Ratings

3) Data structures & algorithms in Java by Robert Lafore

Most of your interview questions will be based on Java SE .
You can do your Java project in Java SE or Java EE (formerly called J2EE) that's your choice.

You must also polish your English language communication skills & problem solving skills


----------



## Desmond (Dec 4, 2014)

Head First Java is a good book, if you can devote time reading it patiently. [MENTION=271931]adityak469[/MENTION] Try to get it second hand if you can.


----------



## JGuru (Dec 15, 2014)

What do companies look for a candidate to get a IT job?

Qualification : BE/BTech/ME/MTech, MCA, MBA etc.,

Percentage    :  60% (Som Companies ask for 70%)

Programming Languages : C/C++, Java, Oracle etc.,

Project       :  Project in C++, Java (JavaSE, JavaEE), C#

Other Skills   : English language (Communication), problem-solving skills (Arithmetic)

*Java Books Recommended*

1) Core Java by C .S Horstmann (2 volumes) - Java language core concepts

2) Java FAQ by Jonni Kanerva - Helps you to answer interview questions

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

4) John Zukowski's Definitive Guide to Swing - Master Java Swing classes

5) Java How To Program by H M Deitel & P J Deitel - Learn how to program using Java language

*Books for Arithmetic Aptitude/ IQ Puzzles*

1) Arithmetic Aptitude by RK Aggarwal

2) Competition Success Review magazine

3) Shakuntala Devi puzzles

Not all candidates get the IT job or any other job. If you go to Bangalore or Chennai - Only 10 out of 10000 get a IT job!!!
So be serious. Study these books , learn programming, practise arithmetic aptitude solutions. 
So work hard, and come up victorious in life.


----------



## Adarsh_Gujurati (Mar 28, 2015)

Great....now make a PG13 tutorial.


----------

