T. Y. B. SC.: (Computer Science)
T. Y. B. SC.: (Computer Science)
(Computer Science)
Laboratory Course II
Programming in Java - CS348
Semester I
This book is mandatory for the completion of the laboratory course. It is a measure of the
performance of the student in the laboratory for the entire duration of the course.
Difficulty Levels
Self Activity: Students should solve these exercises for practice only.
SET A - Easy: All exercises are compulsory.
SET B - Medium: All exercises are compulsory.
Name :
4 Exception Handling
Total out of 30
Total out of 5
Signature of Incharge:
Examiner I:
Examiner II:
Date:
Assignment 1: Java Tools and IDE, Simple Java programs
Objectives
Reading
You should read the following topics before starting this exercise
1. Creating, compiling and running a java program.
2. The java virtual machine.
3. Java tools like javac, java, javadoc, javap and jdb.
4. Java keywords
5. Syntax of class.
Ready Reference
Java Tools
(1) javac:- javac is the java compiler which compiles .java file into .class file(i.e. bytecode).
If the program has syntax errors, javac reports them. If the program is error-free, the output of
this command is one or more .class files.
Syntax:
javac fileName.java
(2) java:- This command starts Java runtime environment, loads the specified .class file and
executes the main method.
Syntax:
java fileName
(3) javadoc:- javadoc is a utility for generating HTML documentation directly from
comments written in Java source code.Javadoc comments have a special form but seems like
an ordinary multiline comment to the compiler.
Syntax of the comment:
/**
A sample doc comment
*/
Syntax:
javadoc [options] [packagenames ] [ sourcefiles ] [@files ]
Where,
packagenames: A series of names of packages, separated by spaces
sourcefiles: A series of source file names, separated by spaces
@files: One or more files that contain packagenames and sourcefiles in any order, one
name per line.
Javadoc creates the HTML documentation on the basis of the javadoc tags used in the source
code files. These tags are described in the table below:
(4) jdb: -
jdb helps you find and fix bugs in Java language programs. This debugger has limited
functionality.
Syntax:
jdb [ options ] [ class ] [ arguments ]
options : Command-line options.
class : Name of the class to begin debugging.
arguments : Arguments passed to the main() method of class.
After starting the debugger, the jdb commands can be executed. The important jdb commands are:
i. help, or?: The most important jdb command, help displays the list of recognized
commands with a brief description.
ii. run: After starting jdb, and setting any necessary breakpoints, you can use this command to
start the execution the debugged application.
iii. cont: Continues execution of the debugged application after a breakpoint, exception, or
step.
iv. print: Displays Java objects and primitive values. For variables or fields of primitive
types, the actual value is printed. For objects, a short description is printed.
Examples:
print MyClass.myStaticField
print myObj.myInstanceField
print i + j + k
print myObj.myMethod()//if myMethod returns non-null
v. dump: For primitive values, this command is identical to print. For objects, it prints
the current value of each field defined in the object. Static and instance fields are
included.
vi. next: The next command advances execution to the next line in the current stack frame.
vii. step: The step commands advances execution to the next line whether it is in the current
stack frame or a called method.
(4) javap: -
The javap tool allows you to query any class and find out its list of methods and constants.
javap [ options ] class
Example: javap java.lang.String
It is a disassembler which allows the bytecodes of a class file to be viewed when used with a
classname and the c option.
javap -c class
T.Y.B.Sc (Comp. Sc.) Lab II, Sem I [Page 2]
Setting CLASSPATH
The classpath is the path that the Java runtime environment searches for classes and other
resource files. The class path can be set using either the classpath option or by setting the
CLASSPATH environment variable.
The -classpath option is preferred because you can set it individually for each application without
affecting other applications and without other applications modifying its value. 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.
About Eclipse
Perspective Switcher
We can switch between
Menubars various perspectives Task List Pane
Full drop down menus plus quick here
access to common functions This contains a list of
tasks to complete
Editor Pane
This is where we edit
our source code
Package Explorer Pane Outline Pane
This is where our This contains a hierarchical
projects/files are listed view of a source file
Miscellaneous Pane
Various components can appear in this
pane typically this contains a console
and a list of compiler problems
1. Sample program
Type the following command: javadoc MyClass.java. See the HTML documentation file
MyClass.html
2. Sample program
/* Program to define a class and an object of the class* /
public class MyClass {
int num;
public MyClass() {
num=0;
}
public MyClass(int num) {
this.num = num;
}
public static void main(String[] args) {
MyClass m1 = new MyClass();
if(args.length > 0)
{
int n = Integer.parseInt(args[0]);
MyClass m2 = new MyClass(n);
System.out.println(m1.num);
System.out.println(m2.num);
}
else
System.out.println(Insufficient arguments);
}
}
Pass one command line argument to the above program and execute it.
Lab Assignments
SET A
1. Using javap, view the methods of the following classes from the lang package:
java.lang.Object , java.lang.String and java.util.Scanner.
2. Compile sample program 2. Type the following command and view the bytecodes.
javap -c MyClass
SET B
1. Write a java program to display the system date and time in various formats shown below:
Current date is : 31/07/2015
Current date is : 07-31-2015
Current date is : Friday July 31 2015
Current date and time is : Fri July 31 16:25:56 IST 2015
Current date and time is : 31/07/15 16:25:56 PM +0530
Current time is : 16:25:56
Current week of year is : 31
Current week of month : 5
Current day of the year is : 212
Note: Use java.util.Date and java.text.SimpleDateFormat class
2. Define a class MyNumber having one private int data member. Write a default constructor to
initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods
isNegative, isPositive, isZero, isOdd, isEven. Create an object in main. Use command line
arguments to pass a value to the object (Hint : convert string argument to integer) and perform the
above tests. Provide javadoc comments for all constructors and methods and generate the html
help file.
Assignment Evaluation
Defining a class.
Creating an array of objects.
Creating a package. (Using package command)
Using packages (Using import command)
Reading
You should read the following topics before starting this exercise:
1. Structure of a class in java.
2. Declaring class reference.
3. Creating an object using new.
4. Declaring an array of references.
5. Creating an array of objects.
6. Syntax of the package and import command.
Ready Reference
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of methodTHE JAVA LANGUAGE
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Example
class Student{
private int rollNumber; private String name;
Student() //constructor
{
rollNumber = 0; name = null;
}
Student(int rollNumber, String name)
{
this.rollNumber = rollNumber; this.name = name;
}
void display()
{
System.out.println("Roll number = " + rollNumber);
System.out.println(" Name = " + name);
}
}
To convert the argument from String to any type, use Wrapper classes.
Method Purpose
Byte.parseByte Returns byte equivalent of a String
Short.parseShort Returns the short equivalent of a String
Integer.parseInt Returns the int equivalent of a String
Long.parseLong Returns the long equivalent of a String
Float.parseFloat Returns the float equivalent of a String
Double.parseDouble Returns the double equivalent of a String
Simple I/O
To read a String from the console, use the following code:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Or
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Packages:
A package is a collection of related classes and interfaces. It provides a mechanism for
compartmentalizing classes. The Java API is organized as a collection of several predefined
packages. The java.lang package is the default package included in all java programs. The
commonly used packages are:
java.lang Language support classes such as Math, Thread, String
java.util Utility classes such as LinkedList, Vector , Date.
java.io Input/Output classes
java.awt For graphical user interfaces and event handling.
javax.swing For graphical user interfaces
java.net For networking
java.applet For creating applets.
Creating a package
To create a user defined package, the package statement should be written in the source code file.
This statement should be written as the first line of the program. Save the program in a directory
of the same name as the package.
package packageName;
Accessing a package
To access classes from a package, use the import statement.
import packageName.*; //imports all classes
import packageName.className; //imports specified class
Note that the package can have a hierarchy of subpackages. In that case, the package name should
be qualified using its parent packages. Example: project.sourcecode.java
Here, the package named project contains one subpackage named sourcecode which contains a
subpackage named java.
Access Rules
The access rules for members of a class are given in the table below.
Accessible to public protected none private
Same class Yes Yes Yes Yes
Class in same package Yes Yes Yes No
Subclass (in other package) Yes Yes No No
Non subclass in Other package Yes No No No
Self Activity
1. Sample program to create objects , demonstrate use of toString and static keyword.
class Student {
int rollNumber;
String name;
static String classTeacher;
Student(int r, String n) {
rollNumber = r; name = n;
}
static void assignTeacher(String name) {
classTeacher = name;
}
public String toString() {
return "[ " + rollNumber + "," + name + "," + classTeacher +"
2. Sample program to read Student roll number and name from the console and display
them (Using BufferedReader).
import java.io.*;
class ConsoleInput
{
public static void main(String[] args) throws IOException
{
int rollNumber;
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the roll number: ");
rollNumber = Integer.parseInt(br.readLine());
System.out.println(" Enter the name: ");
name = br.readLine();
System.out.println(" Roll Number = " + rollNumber);
System.out.println(" Name = " + name);
}
}
3. Sample program to read Student roll number and name from the console and display
them (Using Scanner class).
import java.util.Scanner;
class ScannerTest{
public static void main(String args[])throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno and name :");
int rollno=sc.nextInt();
String name=sc.next();
System.out.println("Rollno:"+rollno+" Name:"+name);
sc.close();
}
}
Lab Assignments
SET A
1. Define a Student class (roll number, name, percentage). Define a default and parameterized
constructor. Keep a count of objects created. Create objects using parameterized constructor and
display the object count after each object is created. (Use static member and method). Also
display the contents of each object.
2. Modify the above program to create n objects of the Student class. Accept details from the user
for each object. Define a static method sortStudent which sorts the array on the basis of
percentage.
SET B
1. Create a package named Series having three different classes to print series:
a. Prime numbers b. Fibonacci series c. Squares of numbers
Write a program to generate n terms of the above series.
2. Write a Java program to create a Package SY which has a class SYMarks (members
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a class
TYMarks (members Theory, Practicals). Create n objects of Student class (having rollNumber,
name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects and calculate
the Grade (A for >= 70, B for >= 60 C for >= 50 , Pass Class for > =40 else FAIL) and
display the result of the student in proper format.
Assignment Evaluation
Reading
You should read the following topics before starting this exercise:
1. Concept of inheritance.
2. Use of extends keyword.
3. Concept of abstract class.
4. Defining an interface.
5. Use of implements keyword.
Ready Reference
Types of Inheritance
Access in subclass
The following members can be accessed in a subclass:
i) public or protected superclass members.
ii) Members with no specifier if subclass is in same package.
Abstract class
An abstract class is a class which cannot be instantiated. It is only used to create subclasses. A
class which has abstract methods must be declared abstract. An abstract class can have data
members, constructors, method definitions and method declarations.
abstract class ClassName
{
...
}
Abstract method
An abstract method is a method which has no definition. The definition is provided by the
subclass.
abstract returnType method(arguments);
Interface
An interface is a pure abstract class i.e. it has only abstract methods and final variables. An
interface can be implemented by multiple classes.
interface InterfaceName
{
//abstract methods
//final variables
}
T.Y.B.Sc (Comp. Sc.) Lab II, Sem I [Page 12]
Example:
interface MyInterface
{
void method1();
void method2();
int size= 10; //final and static
}
class MyClass implements MyInterface {
//define method1 and method2
}
Self Activity
Lab Assignments
SET A
1. Define a class Employee having private members id, name, department, salary. Define
default and parameterized constructors. Create a subclass called Manager with private member
bonus. Define methods accept and display in both the classes. Create n objects of the Manager
class and display the details of the manager having the maximum total salary (salary+bonus)
3. Write a Java program to create a super class Vehicle having members Company and price.
Derive 2 different classes LightMotorVehicle (members mileage) and HeavyMotorVehicle
(members capacity-in-tons). Accept the information for n vehicles and display the information
in appropriate form. While taking data, ask the user about the type of vehicle first.
SET B
1. Define an abstract class Staff with members name and address. Define two sub-classes of this
class FullTimeStaff (department, salary) and PartTimeStaff (number-of-hours, rate-per-
hour). Define appropriate constructors. Create n objects which could be of either FullTimeStaff
or PartTimeStaff class by asking the users choice. Display details of all FullTimeStaff objects
and all PartTimeStaff objects.
Assignment Evaluation
Reading
You should read the following topics before starting this exercise:
1. Concept of Exception
2. Exception class hierarchy.
3. Use of try, catch, throw, throws and finally keywords
4. Defining user defined exception classes
Ready Reference
Exception: An exception is an abnormal condition that arises in a code at run time.
When an exception occurs,
1. An object representing that exception is created.
2. The method may handle the exception itself.
3. If the method cannot handle the exception, it throws this exception object to the method
which called it.
4. The exception is caught and processed by some method or finally by the default java
exception handler.
Error Exception
Unchecked
errors RuntimeException Checked
exceptions
Unchecked
exceptions
Exception Handling keywords
Exception handling in java is managed using 5 keywords: try , catch , throw, throws,
finally
Syntax
try
{
// code that may cause an exception
}
catch (ExceptionType1 object)
{
// handle the exception
}
catch (ExceptionType2 object)
{
// handle the exception
}
finally
{
// this code is always executed
}
throw keyword:
The throw keyword is used to throw an exception object or to rethrow an exception.
throw exceptionObject;
Example:
catch(NumberFormatException e)
{
System.out.println(Caught and rethrown ) ;
throw e;
}
We can explicitly create an exception object and throw it. For example:
throw new NumberFormatException();
throws keyword:
If the method cannot handle the exception, it must declare a list of exceptions it may cause. This
list is specified using the throws keyword in the method header. All checked exceptions muct be
caught or declared.
Syntax:
returnType methodName(arguments) throws ExceptionType1
[,ExceptionType2...]
{
//method body
}
Example:
void acceptData() throws IOException
{
//code
}
Exception Types:
There are two types of Exceptions, Checked exceptions and Unchecked exceptions. Checked
exceptions must be caught or rethrown. Unchecked exceptions do not have to be caught.
Unchecked Exceptions:
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
T.Y.B.Sc (Comp. Sc.) Lab II, Sem I [Page 16]
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Checked Exceptions:
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Self Activity
Lab Assignments
SET A
1. Define a class CricketPlayer (name, no_of_innings, no_times_notout, total_runs, bat_avg).
Create an array of n player objects. Calculate the batting average for each player using a static
method avg(). Handle appropriate exception while calculating average. Define a static method
sortPlayer which sorts the array on the basis of average. Display the player details in sorted
order.
2. Define a class SavingAccount (acNo, name, balance). Define appropriate constructors and
operations withdraw(), deposit() and viewBalance(). The minimum balance must be 500.
Create an object and perform operations. Raise user defined InsufficientFundsException when
balance is not sufficient for withdraw operation.
SET B
1. Define a class MyDate (day, month, year) with methods to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception InvalidDateException
if the date is invalid.
Examples of invalid dates : 12 15 2015, 31 6 1990, 29 2 2001
Assignment Evaluation
Reading
You should read the following topics before starting this exercise:
1. Concept of streams
2. Types of streams
3. Byte and Character stream classes.
4. The File class
Ready Reference
java.io.File class
This class supports a platform-independent definition of file and directory names. It also
provides methods to list the files in a directory, to check the existence, readability, writeability,
type, size, and modification time of files and directories, to make new directories, to rename files
and directories, and to delete files and directories.
Constructors:
public File(String path);
public File(String path, String name);
public File(File dir, String name);
Example
File f1=new File(/home/java/a.txt);
Methods
1. boolean canRead()- Returns True if the file is readable.
2. boolean canWrite()- Returns True if the file is writeable.
3. String getName()- Returns the name of the File with any directory names omitted.
4. boolean exists()- Returns true if file exists
5. String getAbsolutePath()- Returns the complete filename. Otherwise, if the File is a
relative file specification, it returns the relative filename appended to the current working
directory.
6. String getParent()- Returns the directory of the File. If the File is an absolute
specification.
7. String getPath()- Returns the full name of the file, including the directory name.
8. boolean isDirectory()- Returns true if File Object is a directory
9. boolean isFile()- Returns true if File Object is a file
10. long lastModified()- Returns the modification time of the file (which should be used for
comparison with other file times only, and not interpreted as any particular time format).
11. long length()- Returns the length of the file.
12. boolean delete()- deletes a file or directory. Returns true after successful deletion of a
file.
13. boolean mkdir ()- Creates a directory.
14. boolean renameTo (File dest)- Renames a file or directory. Returns true after successful
renaming
There are four top level abstract stream classes: InputStream, OutputStream, Reader, and Writer.
1. InputStream. A stream to read binary data.
2. OutputStream. A stream to write binary data.
3. Reader. A stream to read characters.
4. Writer. A stream to write characters.
T.Y.B.Sc (Comp. Sc.) Lab II, Sem I [Page 20]
ByteStream Classes
a. InputStream Methods-
1. int read ()- Returns an integer representation of next available byte of input.-1 is returned at
the stream end.
2. int read (byte buffer[ ])- Read up to buffer.length bytes into buffer & returns actual number
of bytes that are read. At the end returns 1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to numbytes bytes
into buffer starting at buffer[offset]. Returns actual number of bytes that are read. At the end
returns 1.
4. void close()- to close the input stream
5. void mark(int numbytes)- places a mark at current point in input stream & remain valid till
number of bytes are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream beginning.
7. long skip(long numbytes)- skips number of bytes.
8. int available()- Returns number of bytes currently available for reading.
b. OutputStream Methods-
1. Reader : Reader is an abstract class that defines Javas method of streaming character input.
All methods in this class will throw an IOException.
Methods in this class-
1. int read ()- Returns an integer representation of next available character from invoking
stream. -1 is returned at the stream end.
2. int read (char buffer[ ])- Read up to buffer.length chacters to buffer & returns actual number
of characters that are successfully read. At the end returns 1.
3. int read(char buffer[ ], int offset, int numchars)- Attempts to read up to numchars into
buffer starting at buffer[offset]. Returns actual number of characters that are read. At the end
returns 1.
4. void close()- to close the input stream
5. void mark(int numchars)- places a mark at current point in input stream & remain valid till
number of characters are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream beginning.
7. long skip(long numchars)- skips number of characters.
8. int available()- Returns number of bytes currently available for reading.
b. Writer : Is an abstract class that defines streaming character output. All the methods in this
class returns a void value & throws an IOException. The methods are-
Self Activity
1. Sample program
/* Program to count occurrences of a string within a text file*/
import java.io.*;
import java.util.*;
public class TextFileReadApp
{
public static void main (String arg[]) {
File f = null;
// Get the file from the argument line.
if (arg.length > 0)
f = new File (arg[0]);
if (f == null || !fe.exists ()) {
System.exit(0);
}
2. Sample program
/* Program to write and read primitive types to a file */
import java.io.*;
class PrimitiveTypes {
public static void main(String args[]) throws IOException {
FileOutputStream fos=new FileOutputStream("info.dat");
DataOutputStream dos=new DataOutputStream(fos);
dos.writeInt(25); dos.writeBoolean(true);
dos.writeChar('A'); dos.writeDouble(5.45);
fos.close();
3. Sample program
/* Program to read integers from a file using Scanner class*/
import java.io.*;
import java.util.*;
class ReadIntegers {
public static void main(String args[]) throws IOException {
FileReader file = new FileReader("numbers.txt");
Scanner sc = new Scanner(file);
int sum=0, num;
while(sc.hasNext())
{
num = sc.nextInt();
System.out.println("Number = "+ num);
sum = sum+num;
}
System.out.println("The sum = "+ sum);
file.close();
}
}
SET A
1. Write a program to accept a string as command line argument and check whether it is a file or
directory. If it is a directory, list the contents of the directory, count how many files the
directory has and delete all files in that directory having extension .txt. (Ask the user if the
files have to be deleted). If it is a file, display all information about the file (path, size,
attributes etc).
2. Write a menu driven program to perform the following operations on a text file phone.txt
which contains name and phone number pairs. The menu should have options:
i. Search name and display phone number
ii. Add a new name-phone number pair.
SET B
1. Write a program to read item information (id, name, price, qty) in file item.dat. Write a menu
driven program to perform the following operations using Random access file:
i. Search for a specific item by name. ii. Find costliest item. ii. Display all items and total cost
1. Accept the names of two files and copy the contents of the first to the second. Add Author
name and Date in comments in the beginning of file. Add the comment end of file at the
end.
2. Write a Java program to accept an option, string and file name using command line argument.
Perform following operations:
a. If no option is passed then print all lines in the file containing the string.
b. If the option passed is c then print the count of lines containing the string.
c. If the option passed is v then print the lines not containing the string.
Assignment Evaluation
Reading
You should read the following topics before starting this exercise
1. AWT and Swing concepts.
2. Layout managers in java
3. Containers and Components
4. Adding components to containers
5. Event sources, listeners and delegation event model
6. Adapter classes
7. Applet tag, Applet class, applet methods
Ready Reference
Graphical User Interface elements are implemented in two java packages AWT and Swing.
Swing is the newer package and swing classes are based on AWT classes.
Swing Architecture:
The design of the Swing component classes is based on the Model-View-Controller architecture,
or MVC.
1. The model stores the data.
2. The view creates the visual representation from the data in the model.
3. The controller deals with user interaction and modifies the model and/or the view.
Swing Classes:
The following table lists some important Swing classes and their description.
Class Description
Box Container that uses a BoxLayout
JApplet Base class for Swing applets
JButton Selectable component that supports text/image display
JCheckBox Selectable component that displays state to user
JCheckBoxMenuItem Selectable component for a menu; displays state to user
JColorChooser For selecting colors
JComboBox For selecting from a drop-down list of choices
JComponent Base class for Swing components
JDesktopPane Container for internal frames
JDialog Base class for pop-up subwindows
JEditorPane For editing and display of formatted content
JFileChooser For selecting files and directories
JFormattedTextField For editing and display of a single line of formatted text
JFrame Base class for top-level windows
JInternalFrame Base class for top-level internal windows
Layout Manager
The job of a layout manager is to arrange components on a container. Each container has a
layout manager associated with it. To change the layout manager for a container, use the
setLayout() method.
Syntax
setLayout(LayoutManager obj)
3 4 5 6
WEST CENTER EAST
4 5 6
7 8 9
10 11 12
SOUTH
1
Card2 1
Card1
1 2 3 2 1 2
2 3 4
1
3 3 4
5 6
7
4 2
8 9
Examples:
JPanel p1 = new JPanel()
p1.setLayout(new FlowLayout());
p1.setLayout(new BorderLayout());
p1.setLayout(new GridLayout(3,4));
Important Containers:
1. JFrame This is a top-level container which can hold components and containers like panels.
Constructors
JFrame()
JFrame(String title)
Important Methods
setSize(int width, int height) -Specifies size of the frame in pixels
setLocation(int x, int y) -Specifies upper left corner
setVisible(boolean visible) -Set true to display the frame
setTitle(String title) -Sets the frame title
setDefaultCloseOperation(int
-Specifies the operation when frame is closed. The modes are:
mode)
JFrame.EXIT_ON_CLOSE JFrame.DO_NOTHING_ON_CLOSE
JFrame.HIDE_ON_CLOSE JFrame.DISPOSE_ON_CLOSE
pack() -Sets frame size to minimum size required to hold components
2. JPanel This is a middle-level container which can hold components and can be added to
other containers like frame and panels.
Constructors
public javax.swing.JPanel(java.awt.LayoutManager, boolean);
public javax.swing.JPanel(java.awt.LayoutManager);
public javax.swing.JPanel(boolean);
public javax.swing.JPanel();
2. Button
A Swing button can display both text and an image. The underlined letter in each button's
text shows the mnemonic which is the keyboard alternative.
Constructors-
JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)
Methods-
void setDisabledIcon(Icon) void setPressedIcon(Icon)
void setSelectedIcon(Icon) void setRolloverIcon(Icon)
String getText() void setText(String)
Event- ActionEvent
3. Check boxes
Class- JCheckBox
Constructors-
JCheckBox(Icon i) JCheckBox(Icon i,booean state)
JCheckBox(String s) JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i) JCheckBox(String s, Icon I, boolean state)
Methods-
void setSelected(boolean state) String getText()
void setText(String s)
Event- ItemEvent
4. Radio Buttons
Class- JRadioButton
Constructors-
JRadioButton (String s) JRadioButton(String s, boolean state)
JRadioButton(Icon i) JRadioButton(Icon i, boolean state)
JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, boolean
state)
JRadioButton()
5. Combo Boxes
Class- JComboBox
Constructors- JComboBox()
Methods-
void addItem(Object) Object getItemAt(int)
Object getSelectedItem() int getItemCount()
Event- ItemEvent
6. List
Constructor- JList(ListModel)
List models-
1. SINGLE_SELECTION - Only one item can be selected at a time. When the user selects
an item, any previously selected item is deselected first.
2. SINGLE_INTERVAL_SELECTION- Multiple, contiguous items can be selected.
When the user begins a new selection range, any previously selected items are deselected
first.
3. MULTIPLE_INTERVAL_SELECTION- The default. Any combination of items can
be selected. The user must explicitly deselect items.
Methods-
boolean isSelectedIndex(int) void setSelectedIndex(int)
void setSelectedIndices(int[]) void setSelectedValue(Object, boolean)
void setSelectedInterval(int, int) int getSelectedIndex()
int getMinSelectionIndex() int getMaxSelectionIndex()
int[] getSelectedIndices() Object getSelectedValue()
Object[] getSelectedValues()
Example-
listModel = new DefaultListModel();
listModel.addElement("India");
listModel.addElement("Japan");
listModel.addElement("France");
listModel.addElement("Denmark");
list = new JList(listModel);
Event- ActionEvent
7. Text classes
All text related classes are inherited from JTextComponent class
a. JTextField
Creates a text field. The int argument specifies the desired width in columns. The String
argument contains the field's initial text. The Document argument provides a custom document
for the field.
Constructors-
JTextField() JTextField(String)
JTextField(String, int) JTextField(int)
JTextField(Document, String, int)
c. JTextArea
Represents a text area which can hold multiple lines of text
Constructors-
JTextArea (int row, int cols)
JTextArea (String s, int row, int cols)
Methods-
void setColumns (int cols) void setRows (int rows)
void append(String s) void setLineWrap (boolean)
8. Dialog Boxes
Types-
1. Modal- wont let the user interact with the remaining windows of application until
first deals with it. Ex- when user wants to read a file, user must specify file name
before prg. can begin read operation.
2. Modeless dialog box- Lets the user enters information in both, the dialog box &
remainder of application ex- toolbar.
Swing has a JOptionPane class, that lets you put a simple dialog box.
Methods in JOption Class
1. static void showMessageDialog()- Shows a message with ok button.
2. static int showConfirmDialog()- shows a message & gets users options from set
of options.
3. static int showOptionDialog- shows a message & get users options from set of
options.
4. String showInputDialog()- shows a message with one line of user input.
Event handling is an important part of GUI based applications. Events are generated by event
sources. A mouse click, Window closed, key typed etc. are examples of events.
All java events are sub-classes of java.awt.AWTEvent class.
Event Description
ComponentEvent Indicates that a component object (e.g. Button, List, TextField) is moved, resized,
rendered invisible or made visible again.
FocusEvent Indicates that a component has gained or lost the input focus.
KeyEvent Generated by a component object (such as TextField) when a key is pressed,
released or typed.
MouseEvent Indicates that a mouse action occurred in a component. E.g. mouse is pressed,
releases, clicked (pressed and released), moved or dragged.
ContainerEvent Indicates that a containers contents are changed because a component was added
or removed.
WindowEvent Indicates that a window has changed its status. This low level event is generated
by a Window object when it is opened, closed, activated, deactivated, iconified,
deiconified or when focus is transferred into or out of the Window.
2. High-Level Events: High-level (also called as semantic events) events encapsulate the
meaning of a user interface component. These include following events.
Event Description
ActionEvent Indicates that a component-defined action occurred. This high-level event is
generated by a component (such as Button) when the component-specific action
occurs (such as being pressed).
AdjustmentEvent The adjustment event is emitted by Adjustable objects like scrollbars.
ItemEvent Indicates that an item was selected or deselected. This high-level event is
generated by an ItemSelectable object (such as a List) when an item is selected or
deselected by the user.
TextEvent Indicates that an objects text changed. This high-level event is generated by an
object (such as TextComponent) when its text changes.
The following table lists the events, their corresponding listeners and the method to add the
listener to the component.
Event Event Source Event Listener Method to add listener to
event source
Low-level Events
ComponentEvent Component ComponentListener addComponentListener()
FocusEvent Component FocusListener addFocusListener()
KeyEvent Component KeyListener addKeyListener()
MouseEvent Component MouseListener addMouseListener()
MouseMotionListener addMouseMotionListener()
ContainerEvent Container ContainerListener addContainerListener()
WindowEvent Window WindowListener addWindowListener()
High-level Events
ActionEvent Button ActionListener addActionListener()
List
MenuItem
TextField
java.lang.Object
java.util.EventObject
java.awt.AWTEvent
KeyEvent MouseEvent
Listener Methods:
Methods Description
ComponentListener
componentResized(ComponentEvent e) Invoked when components size changes.
componentMoved(ComponentEvent e) Invoked when components position changes.
componentShown(ComponentEvent e) Invoked when component has been made visible.
componentHidden(ComponentEvent e) Invoked when component has been made invisible.
FocusListener
focusGained(FocusEvent e) Invoked when component gains the keyboard focus.
focusLost(FocusEvent e) Invoked when component loses the keyboard focus.
KeyListener
keyTyped(KeyEvent e) Invoked when a key is typed.
keyPressed(KeyEvent e) Invoked when a key is pressed.
keyReleased(KeyEvent e) Invoked when a key is released.
MouseListener
mouseClicked(MouseEvent e) Invoked when a mouse button is clicked (i.e. pressed and
released) on a component.
mousePressed(MouseEvent e) Invoked when a mouse button is pressed on a component.
mouseReleased(MouseEvent e) Invoked when a mouse button is released on a component.
mouseEntered(MouseEvent e) Invoked when a mouse enters a component.
mouseExited(MouseEvent e) Invoked when a mouse exits a component.
MouseMotionListener
mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and
then dragged.
mouseMoved(MouseEvent e) Invoked when a the mouse cursor is moved on to a component
but mouse button is not pressed.
ContainerListener
componentAdded(ContainerEvent e) Invoked when a component is added to the container.
componentRemoved(ContainerEvent e) Invoked when a component is removed from the container.
WindowListener
Adapter Classes:
All high level listeners contain only one method to handle the high-level events. But most low level
event listeners are designed to listen to multiple event subtypes (i.e. the MouseListener listens to
mouse-down, mouse-up, mouse-enter, etc.). AWT provides a set of abstract adapter classes, which
implements each listener interface. These allow programs to easily subclass the Adapters and override
only the methods representing event types they are interested in, instead of implementing all methods
in listener interfaces.
Applet
Applets are small java programs which are executed and displayed in a java compatible web browser.
Creating an applet
All applets are subclasses of the java.applet.Applet class. You can also create an applet by extending
the javax.swing.JApplet class. The syntax is:
Running an applet
1. Compile the applet code using javac
2. Use the java tool appletviewer to view the applet (embed the APPLET tag in comments
in the code)
3. Use the APPLET tag in an HTML page and load the applet in a browser
Using appletviewer:
1. Write the HTML APPLET tag in comments in the source file.
2. Compile the applet source code using javac.
3. Use appletviewer ClassName.class to view the applet.
Using browser:
1. Create an HTML file containing the APPLET tag.
2. Compile the applet source code using javac.
3. In the web browser, open the HTML file.
Examples:
1. <applet code=MyApplet width=200 height=200 archive="files.jar">
</applet>
2. <applet code=Simple.class width=100 height=200 codebase=example/>
</applet>
The PARAM tag allows us to pass information to an applet when it starts running.
A parameter is a NAME VALUE pair. Every parameter is identified by a name and it has a
value.
< PARAM NAME = AttributeName VALUE = AttributeValue />
Example:
<APPLET NAME = "MyApplet.class" WIDTH = 100 HEIGHT = 100>
<PARAM NAME = "ImageSource" VALUE = "project/images/">
<PARAM NAME = "BackgroundColor" VALUE = "0xc0c0c0">
<PARAM NAME = "FontColor" VALUE = "Red">
</APPLET>
The Applet can retrieve information about the parameters using the getParameter() method.
String getParameter(String parameterName);
Example:
String dirName = getParameter(ImageSource);
Color c = new Color( Integer.parseInt(getParameter(BackgroundColor)));
Self Activity
1. Sample program
/* Program to demonstrate Button and text field */
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame implements
ActionListener
{
JTextField jtf; JButton jb;
public JButtonDemo()
{
setLayout(new FlowLayout());
jtf=new JTextField(15);
add (jtf);
2. Sample program
/* Program to demonstrate Combobox */
import java.awt.*; import javax.swing.*; import java.awt.event.*;
public class JCdemo extends JFrame implements ItemListener
{
JTextField jtf; JCheckBox jcb1, jcb2;
public JCdemo()
{
setLayout(new FlowLayout());
jcb1=new JCheckBox("Swing Demos");
jcb1.addItemListener(this); add(jcb1);
jcb2=new JCheckBox("Java Demos");
jcb2.addItemListener(this); add(jcb2);
3. Sample program
/* Program to demonstrate Radio Button */
import java.awt.*; import javax.swing.*; import java.awt.event.*;
public class JRdemo extends JFrame implements ActionListener
{
JTextField jtf;
JRadioButton jrb1,jrb2; ButtonGroup bg;
public JRdemo()
{
setLayout(new FlowLayout());
bg=new ButtonGroup();
jrb1=new JRadioButton("A");
jrb1.addActionListener(this);
jrb2=new JRadioButton("B");
jrb2.addActionListener(this);
bg.add(jrb2); add(jrb2);
jtf=new JTextField(5); add(jtf);
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{ jtf.setText(ae.getActionCommand()); }
public static void main(String[] args)
{ new JRdemo(); }
}
4. Sample program
/* Program to handle mouse movements and key events on a frame*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
5. Sample program
/* Program to display a message in an applet*/
import java.awt.*;
import java.applet.*;
/*
<applet code="MyApplet.class" width=200 height=100>
</applet>
6. Sample program
/* Applet with components*/
import java.awt.*;
import javax.swing.* ;
import java.applet.*;
/*
<applet code="MyApplet.class" width=200 height=100>
</applet>
*/
public class MyApplet extends Applet
{
JPanel p; JTextField t; JButton b;
public void init()
{
p = new JPanel();
p.setLayout(new FlowLayout());
t = new JTextField(20);
b = new JButton("Click");
p.add(t); p.add(b);
add(p);
}
}
Save this as MyApplet.java Compile the file. Execute it using command appletviewer
MyApplet.class
Lab Assignments
SET A
1. Write a program to create the following GUI and apply the changes to the text in the TextField.
3. Create an Applet which displays a message in the center of the screen. The message indicates
the events taking place on the applet window. Handle events like mouse click, mouse moved,
mouse dragged, mouse pressed, and key pressed. The message should update each time an event
occurs. The message should give details of the event such as which mouse button was pressed,
which key is pressed etc. (Hint: Use repaint(), KeyListener, MouseListener, MouseEvent method
getButton, KeyEvent methods getKeyChar)
SET B
2. Write a menu driven program to perform the following operations on a set of integers. The
Load operation should generate 50 random integers (2 digits) and display the numbers on the
screen. The save operation should save the numbers to a file numbers.txt. The Compute menu
provides various operations and the result is displayed in a message box. The Search operation
accepts a number from the user in an input dialog and displays the search result in a message
dialog. The sort operation sorts the numbers and displays the sorted data on the screen.
1.Create an application in Java using swing that will move star towards up, down, left and right.
Display appropriate message if it crosses the boundary. Design the screen as shown:
Left or Up is Up is Right or
Up is error error Up is UP
error error
Left is Right is
error error Down
Left is Right is
Left
error
Left or
*
Down is Down is
error
Right or
Right
Down is error error down is
error error
Label Field
2. Create a GUI and program for number conversion from decimal to binary, octal and
hexadecimal when the user clicks on Calculate.
Assignment Evaluation