Friday, November 30, 2012

Java Exercise #69: Key Event Demo

This exercise is to demonstrate Key Event. Key events enables the use of keys to control and perform actions. A key event is fired whenever a key is pressed, released or typed on a component.

Exercise: Write a program prints the character key pressed on a panel and help move it using the arrow keys

Download Code: Key Event

Thursday, November 29, 2012

Java Exercise #68: Mouse Event - Dragging message with Mouse

This exercise is to demonstrate Mouse events. MouseEvent inherits InputEvent. There are two listener interfaces MouseListener and MouseMotionListener. This exercise is a demo on MouseMotionListener

Exercise: Write a program that drags a message with the mouse on a panel

Download Code: Mouse Drag Message

Wednesday, November 28, 2012

Java Exercise #67: Handling Window Events

Any subclass of a Window class can fire window events: window opened, window closed, window closing, window activated, window deactivated, window iconified and window de-iconified. This program creates a frame that listens to the window event and displays the message.

Exercise: Write a program that demonstrates Window Events and Window Listener


Window Activated
Window Opened
Window Iconified
Window Deactivated
Window Deiconified
Window Activated
Window Deactivated
Window Iconified



Download Code: Window Event Demo

Monday, November 26, 2012

Java Exercise #66: Control Ball

Exercise: Write a program that uses two buttons to control the size of the circle drawn on the GUI.

Download Code: Control Ball

Java Exercise #65: Simple Event Demo

This exercise is to demonstrate simple Event handling in Java GUI. Buttons are source of ActionEvent. Clicking a button invokes the actionPerformed method on the registered listeners. In this implementation, it will invoke getActionCommand() which by default returns the label of the button. The program also uses the event.getWhen() to return the time in long when the event was generated

This implementation also uses an inner class to create listener instance.

Exercise: Write a program that creates two buttons and print event information when clicked!


The OK button is clicked at 
Mon Nov 26 05:52:43 IST 2012
The Cancel button is clicked at 
Mon Nov 26 05:52:46 IST 2012
The Cancel button is clicked at 
Mon Nov 26 05:52:47 IST 2012
The OK button is clicked at 
Mon Nov 26 05:52:49 IST 2012
The OK button is clicked at 
Mon Nov 26 06:01:12 IST 2012


Download Code: Event Demo

Sunday, November 25, 2012

Java Exercise #64: Display Image

Image icons can be used to display image on labels and buttones. However, ImageIcon displays a fixed size image. We can use the Image class to display images in flexible sizes.

ImageObserver is an asynchronous update interface that receives notifications of image information as the image is constructed. The Component class implements ImageObserver and hence all GUI Components is an instance of ImageObserver. Graphic's drawImage can then be used to draw the image

Exercise: Write a program that draws the following image.

Download Code: Draw Image

Saturday, November 24, 2012

Java Exercise #63: Still Clock

Exercise: Write a program that creates the following Still Clock.

Download Code: Still Clock

Friday, November 23, 2012

Java Exercise #62: Message Panel

This exercise is to develop a useful class that displays a message in the panel. The class enables user to set the location of the message, center the message and move the message with specified interval.

Exercise: Write a program that creates a message panel that helps user to center the message or even move it.

Download Code: Message Panel

Thursday, November 22, 2012

Java Exercise #61: Centering Message on Panel

This exercise is to learn to write a String on a panel while centering it. To do so, we need to use the FontMetrics class to measure the exact height and width of the String

Exercise: Write a program that writes a String centered on the panel.

Download Code: Center Message

Wednesday, November 21, 2012

Java Exercise #60: Drawing Polygon on Panel

Exercise: Write a program that creates the following GUI with a Polygon painted on the panel

Download Code: Drawing Polygon

Tuesday, November 20, 2012

Java Exercise #59: Drawing Arcs

Exercise: Write a program that creates the following GUI with arcs painted on the panel

Download Code: Drawing Arcs

Monday, November 19, 2012

Java Exercise #58: Drawing Figures on Panel

Exercise: Write a program that draws figures on the GUI

Download Code: Draw Figures

Sunday, November 18, 2012

Java Exercise #57: Drawing on Panel

This exercise is to learn to draw on panels using the paintComponent(Graphics) method of the component. This method is invoked evry time a component is displayed/redisplayed. The Graphics object is automatically created by the JVM for every visible GUI component and then passed to the paintComponent method.

Panels are invisible and are used as containers. They are used to create the required layout. Panels can also be used for drawing,

Exercise: Write a program that creates a GUI similar to the following on a Panel.

Download Code: Draw on Panel

Saturday, November 17, 2012

Java Exercise #56: Adding images in GUI

Exercise: Write a program that creates the following GUI for added image icons

Download Code: Image Icon GUI

Friday, November 16, 2012

Java Exercise #55: Common Swing Features

Exercise: Write a program that creates the following GUI

Download Code: Swing Features

Java Exercise #54: Create a GUI similar to Microwave interface

Java Panels can also be used as a sub-container where a panel can be added to another panel. This gives better control in developing more compex GUI frames.

Exercise: Write a program that creates a GUI similar to a Microwave Oven interface.

Download Code: Microwave Interface

Thursday, November 15, 2012

Java Exercise #53: Demonstrate Border Layout

The BorderLayout manager divides the window into five areas - East, West, South, North and Center. Components can be added to the container using BorderLayout by using add method with the index as parameter. Index is a constant from BorderLayout.EAST, BorderLayout.WEST, BorderLayout.SOUTH, BorderLayout.NORTH or BorderLayout.CENTER

The components are laid out according to their preferred sizes where they are placed. The North and South components can stretch horizontally, East and West can stretch vertically and Center can stretch bothways.

Exercise: Write a program that demonstrates BorderLayout.

Download Code: Border Layout

Tuesday, November 13, 2012

Java Exercise #52: Demonstrate GridLayout

GridLayout manager arranges components in a matrix/grid formation with the specified number of rows and columns. The components are arranged in the container from left to right in the first row until all the columns are occupied. It then starts with the next row and so on.

With GridLayout, if you resize the frame, the layout remains unchanged.

Exercise: Write a program that demonstrates GridLayout.

Download Code: Grid Layout

Monday, November 12, 2012

Java Exercise #51: Demonstrate Flow Layout

Flow Layout is a simple layout manager in Java GUI. The components are arranged in the container from left to right (depending on the alignment configuration used) in the order in which they are used. When one row is filled, the other row gets started.

You can specify the alignement using the following 3 constants: FlowLayout.LEFT, FlowLayout.RIGHT or FlowLayout.CENTER. Re-arranging the size of the frame, will automatically re-arrange the layout of the components.

Exercise: Write a program that demonstrates Flow Layout.

Download Code: Flow Layout

Sunday, November 11, 2012

Java Exercise #50: Prime Numbers Above Long.MAX_VALUE

The problem is to write a program that finds out the prime numbers greater than Long.MAX_VALUE

Exercise: Write a program that prints five prime numbers greater than Long.MAX_VALUE

The program was running for hours and hence could not determine the output. However, to ensure that the program is fine, I tested the program for lower values.

Download Code: Big Prime Numbers

Saturday, November 10, 2012

Java Exercise #49: Large Factorial

If we need to compute very huge numbers or high-precision floating point values, we need to use BigInteger and BigDecimal classes in the java.math package. Both these classes are immutable and also implements Comparable interface. You can use add, subtract, multiple, reminder etc. methods to perform computations.

Exercise: Write a program that prints the value for 50!


50! is 30414093201713378043612608166064768844377641568960512000000000000

Download Code: Large Factorial

Java Exercise #48: Generic Sort of Comparables

The problem is to write a generic method to sort an array of Comparable objects. The objects are sorted using the compareTo() method of the Comparable interface.

Exercise: Write a program that sorts any generic array of objects that implements Comparable interface


Sorted Integer Objects: 2 3 4 
Sorted Double Objects: -22.1 1.4 3.4 
Sorted Character Objects: J a r 
Sorted String Objects: Fred John Tom 



Download Code: Generic Sort

Java Exercise #47: Click Buttons

The problem is to write a GUI with two buttons - OK and Cancel. The program will print that the user has clicked OK/Cancel button on console.

Exercise: Write a program that creates a Frame with OK and Cancel buttons. Program should print on the console which button the user clicked.


Clicked OK Button
Clicked Cancel Button
Clicked OK Button
Clicked OK Button
Clicked Cancel Button
Clicked Cancel Button



Download Code: Click Buttons

Wednesday, November 7, 2012

Java Exercise #46: Anagram

The problem is to write a method that checks whether two strings are Anagrams.

Two words are anagrams if they contain the same letters in any order. For example, "silent" and "listen" are anagrams.

Exercise: Write a program that prompts the user to enter two strings and verify whether they are anagrams


Enter the first String: garden
Enter the second String: ranged
garden and ranged are anagrams


Enter the first String: gardens
Enter the second String: dangers
gardens and dangers are anagrams


Download Code: Anagrams

Tuesday, November 6, 2012

Java Exercise #45: Counting Digits in a String

The problem is to write a method that counts the number of digits in a String.

This implementation uses Character.isDigit() method to verify whether a character is a digit.

Exercise: Write a program that prompts the user to enter a String and then prints out the number of digits in the String.


Enter string: d#1@bcd23f1gb
Number of digits is: 4

Download Code: Count Digits

Java Exercise #44: Checking Substring

Java provides indexOf method in the String class to check whether a String is a sub-string of another string. The problem is to implement such a function.

This implementation helped me to come to know about labeled break and continue in Java. Default break/continue (non-labeled) breaks or continue from the inner most for, switch, while, do-while statements. However labeled ones help to break from/continue with the outer statements.

Exercise: Write a program that prompts the user to enter two Strings and then verify whether the first String is a sub-string of the second.


Enter the first string: el
Enter the second string: hello
el is a substring of hello

Enter the first string: hello
Enter the second string: al
No substring found



Download Code: Check Sub-String

Sunday, November 4, 2012

Java Exercise #43: Common Prefix

Write a method that returns the common prefix for two strings. For example, the common prefix for "distance" and "disappoint" is "dis". If the strings don't have a common prefix, print there is no common prefix between them.

Exercise: Write a program that prompts the user to enter two strings and display their common prefix.


Enter first string: paddy
Enter second string: wheat
No common prefix!

Enter first string: Display
Enter second string: disappoint
Common prefix is : dis


Download Code: Common Prefix

Saturday, November 3, 2012

Java Exercise #42: Stack of Integers

A stack is a data structure that holds objects in a last-in, first-out fashion.

A stack has many applications. Java Compiler uses a stack to process method invocations. When a method is invoked, its parameter and local variables are pushed to the stack. When the mentod calls another method, the new method's parameters and local variables are pushed into the stock. When the method finishes its work and return to the caller, its associated space is released.

Exercise: Write a program that implements a stack for storing integers. Stack should internally use an array to hold the elements.


Pushing: 
0 1 2 3 4 5 6 7 8 9 
Popping: 
9 8 7 6 5 4 3 2 1 0 



Download Code: Stack of Integers

Friday, November 2, 2012

Java Exercise #41: Choose and Then Read From File

This exercise is to write a program that chooses a file using the dialog box and then prints the content of the file. This program uses JFileChooser to create the dialog box for choosing file and Scanner class for printing the output

Exercise: Write a program that chooses a text file using dialog box and then prints the output



BODY {
font-family: Segoe UI;
font-size: 10pt;
color: 000000;
margin-left: 10 px;
margin-top: 15 px;
background-position: top left;
background-repeat: repeat;
}



Download Code: Choose and Read File

Thursday, November 1, 2012

Java Exercise #40: Replace Text In File

The problem is to write a program that replaces all occurrences of a String in the file. The program uses Scanner class to read from the file and PrintWriter to write to the file.

Exercise: Write a program that replaces all occurrences of a String in a file. Replace "world" with "universe".


####hello_world.txt###
Hello world!
Good Morning world!

###hello_universe.txt###
Hello universe!
Good Morning universe!



Download Code: Replace Text In File