TYBSc CS Java Labbook
TYBSc CS Java Labbook
To be implemented from
Academic Year 2024–2025
Name:
Academic Year:
Assignment Completion Sheet
USCSP 359
Practical course in Object Oriented Programming using Java I
Assignme Assignment Name Marks Teacher
nt No (out of s Sign
1 Java tools, Basics of Java and 5)
Classes and Objects
2 Array of Objects and Packages
3 Inheritance and Interface
4 Exception handling and File
Handling
5 GUI designing and Event
handling
Total (Out of 25)
Viva/Quiz (Out of 5)
-2-
CERTIFICATE
Instructor HOD/Coordinator
SET A
1. Check the methods of String, Scanner, Integer class using javap command.
2. Write a Java program to accept a number from the user and display a
multiplication table of a number. Accept number using Scanner class.
3. Write a Java Program to Reverse a Number. Accept number using command
line argument.
4. Write a Java program to print the sum of elements of the array. Accept ‘n’
array elements from the user.
5. Write a menu driven program to perform the following operations.
i. Calculate the volume of the cylinder. (hint : Volume: π × r2 × h)
ii. Find the factorial of a given number.
iii. Check if the number is Armstrong or not.
iv. Exit
6. Write a program to accept ‘n’ names of countries and display them in
descending order.
7. Write a Java program to display prime numbers in the range from 1 to 100.
SET B
1. Write a Java program create class as MyDate with dd,mm,yy as data
members. Write accept and display methods. Display the date in dd-mm-yy
format.
2. Write a java program which define class Employee with data member as
name and salary. Program store the information of 5 Employees. (Use array
of object)
3. Write a java program to create class Account (accno, accname, balance).
Create an array of “n” Account objects. Define the static method
“sortAccount” which sorts the array on the basis of balance. Display account
details in sorted order.
SET C
1. Define a class Person (id, name, dateofbirth). For dateofbirth create an
object of MyDate class which is created in SET B 1. Define default and
parameterized constructor. Also define accept and display function in Person
and MyDate class. Call constructor and function of MyDate class from
Person class for dateofbirth. Accept the details of n person and display the
details.
-9-
Sample code:
public class Person
{
private int id;
private String name;
private MyDate dob;
private static int cnt=1;
-------
-------
}
Assignment Evaluation
Theory:
Array of Objects: An array that conations class type elements are known as an
array of objects. It stores the reference variable of the object. Before creating an
array of objects, we must create an instance of the class by using the new keyword.
Suppose, we have created a class named Student. We want to keep marks of 20
students. In this case, we will not create 20 separate objects of Student class.
Instead of this, we will create an array of objects, as follows:
Student s[] = new Student[20];
public class Student
{
int marks;
}
public class ArrayOfObjects
{
public static void main(String args[])
{
Student std[] = new Student[3];// array of reference variables of
Student
std[0] = new Student(); // convert each reference variable into Student object
std[1] = new Student();
std[2] = new Student();
std[0].marks = 40; // assign marks to each Student element
std[1].marks = 50;
std[2].marks = 60;
System.out.println("\n students average marks:" +
(std[0].marks+std[1].marks+std[2].marks)/3);
}
}
Package: A java package is a group of similar types of classes, interfaces and sub-
packages. Package in java can be categorized in two form, built-in package and
user-defined package. There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
Advantage of Java Package:
- 11 -
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package: The package keyword is used to create a package
in java.
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to compile java package: If you are not using any IDE, you need to follow
the syntax given below: javac -d directory javafilename
For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
How to run java package program - You need to use fully qualified name e.g.
mypack.Simple etc to run the class.
- 12 -
SET A
1. Write a java program to take 5 integres as input and store it in a array also
print the array.
2. Write a java program to reverse the array.
3. Create a package named “Series” having three different classes to print
series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers
4. Write a java program to generate “n” terms of the above series. Accept n
from user.
SET B
1. Create a package “utility”. Define a class CapitalString under “utility”
package which will contain a method to return String with first letter capital.
Create a Person class (members– name, city) outside the package. Display
the person name with first letter as capital by making use of CapitalString.
2. Write a package for String operation which has two classes Con and Comp.
Con class has to concatenate two strings and comp class compares two
strings. Also display proper message on execution.
SET C
1. 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.
2. Write a java program to search the given number in array and output
position of given number.
3. Write a java to search given number in array use binary search.
Assignment Evaluation
- 13 -
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
- 14 -
Aim: Inheritance allows a new class (subclass) to acquire the properties and
behaviors of an existing class (superclass), enabling developers to create more
complex systems and extend existing functionality without modifying the original
class. Interfaces define a contract for what a class can do, without dictating how it
should do it.
Theory:
Inheritance: Inheritance is one of the feature of Object Oriented Programming
System (OOPs) it allows the child class to acquire the properties (the data
members) and functionality (the member functions) of parent class.
What is child class?: A class that inherits another class is known as child class, it
is also known as derived class or subclass.
What is parent class?: The class that is being inherited by other class is known as
parent class, super class or base class.
SET A
1. Define a “Point” class having members – x,y(coordinates). Define default
constructor and parameterized constructors. Define two subclasses
“ColorPoint” with member as color and subclass “Point3D” with member as
z (coordinate). Write display method to display the details of different types
of Points.
2. Define a class Employee having members – id, name, salary. Define default
constructor. 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 worker having the maximum
total salary (salary + bonus).
3. Create an abstract class “order” having members id, description. Create two
subclasses “Purchase Order” and “Sales Order” having members customer
name and Vendor name respectively. Define methods accept and display in
all cases. Create 3 objects each of Purchase Order and Sales Order and
accept and display details.
SET B
1. Define an interface “Operation” which has methods area(),volume(). Define
a constant PI having a value 3.142. Create a class circle (member – radius),
cylinder (members – radius, height) which implements this interface.
Calculate and display the area and volume.
2. Write a Java program to create a super class Employee(members – name,
salary). Derive a sub-class as Developer(member – projectname). Derive a
sub-class Programmer(member – proglanguage) from Developer. Create
object of Developer and display the details of it. Implement this multilevel
inheritance with appropriate constructor and methods.
3. Define an abstract class Staff with members name and address. Define two
sub-classes of this class – FullTimeStaff(members - department, salary, hra -
8% of salary, da – 5% of salary) and PartTimeStaff(members - number-of-
- 18 -
hours, rate-per-hour). Define appropriate constructors. Write abstract method
as calculateSalary() in Staff class. Implement this method in subclasses.
Create n objects which could be of either FullTimeStaff or PartTimeStaff
class by asking the user‘s choice. Display details of all FullTimeStaff objects
and all PartTimeStaff objects along with their salary.
SET C
1. Create an interface ― CreditCardInterface with method:
viewCreditAmount(), useCard(), payCredit() and increaseLimit(). Create a
class SilverCardCustomer (name, cardnumber (16digits), creditAmount –
initialized to 0, creditLimit-set to 50,000 ) which implements the above
interface. Inherit class GoldCardCustomer from SilverCardCustomer having
the same methods but creditLimit of 1,00,000. Create an object of each
class and perform operations. Display appropriate messages for success or
failure of transactions.(Use method overriding)
i. useCard() method increases the creditAmount by a specific amount upto
creditLimit.
ii. payCredit() reduces the creditAmount by a specific amount.
iii. increaseLimit() increases the creditLimit for GoldCardCustomers (only 3
times, not more than 5000Rs. each time).
Assignment Evaluation
Aim: Exception handling helps in maintaining the normal flow of the application
- 19 -
even when unexpected situations occur. File handling is essential for reading,
writing, and manipulating files, which is a common requirement in many
applications for data storage, configuration, and data processing.
Theory:
Exception Handling: Exception Handling is the mechanism to handle runtime
malfunctions. We need to handle such exceptions to prevent abrupt termination of
program. The term exception means exceptional condition, it is a problem that may
arise during the execution of program. A bunch of things can lead to exceptions,
including programmer error, hardware failures, files that need to be opened cannot
be found, resource exhaustion etc.
Exception: A Java Exception is an object that describes the exception that occurs
in a program. When an exceptional event occurs in java, an exception is said to be
thrown. The code that's responsible for doing something about the exception is
called an exception handler.
Exception class Hierarchy: All exception types are subclasses of class Throwable,
which is at the top of exception class hierarchy.
Exception class is for exceptional conditions that program should catch. This class
is extended to create user specific exception classes. RuntimeException is a
- 20 -
subclass of Exception. Exceptions under this class are automatically defined for
programs. Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself. Stack overflow
is an example of such an error.
Types of Java Exceptions: There are mainly two types of exceptions: checked and
unchecked. An error is considered as the unchecked exception.
1. Checked Exception: The classes that directly inherit the Throwable class
except RuntimeException and Error are known as checked exceptions.
Checked exceptions are checked at compile-time.
Checked Exceptions:
-Exception
-IOException
-FileNotFoundException
-ParseException
-ClassNotFoundException
-CloneNotSupportedException
-InstantiationException
-InterruptedException
-NoSuchMethodException
-NoSuchFieldException
2. Unchecked Exception: The classes that inherit the RuntimeException are
known as unchecked exceptions. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Unchecked Exceptions:
-ArrayIndexOutOfBoundsException
-ClassCastException
-IllegalArgumentException
-IllegalStateException
-NullPointerException
-ArithmeticException
3. Error: Error is irrecoverable. Some example of errors are
OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling Mechanism: In java, exception handling is done using
five keywords,
Keyword Description
- 21 -
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It
is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.
- 22 -
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
The Java throw keyword is used to throw an exception explicitly.
public class TestThrow
{
public static void validate(int age)
{
if(age<18)
{
throw new ArithmeticException("Person is not eligible to
vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[])
{
TestThrow.validate(13);
System.out.println("rest of the code...");
}
}
User defined Exception: You can also create your own exception sub class simply
- 23 -
by extending java Exception class. You can define a constructor for your Exception
sub class (not compulsory) and you can override the toString()function to display
your customized message on catch.
class NegativeNumberException extends Exception
{
public NegativeNumberException (String str)
{
super(str);
}
}
public class TestUser
{
public static void main(String args[])
{
try
{
int n = Integer.parseInt(args[0]);
if (n<0)
{
throw new NegativeNumberException (n+" is
negative");
}
}
catch (NegativeNumberException e)
{
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
}
Java I/O: Java I/O (Input and Output) is used to process the input and produce the
output. Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
Stream: A stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
- 24 -
Java File Class: The File class is an abstract representation of file and directory
pathname. A pathname can be either absolute or relative. The File class have
several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of
a directory etc.
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract pathname and a
child) child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname
string into an abstract pathname.
File(String parent, String It creates a new File instance from a parent pathname string and a
child) child pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI into
an abstract pathname.
- 25 -
URI toURI() It constructs a file: URI that represents this abstract pathname.
File[] listFiles() It returns an array of abstract pathnames denoting the files in the
directory denoted by this abstract pathname
long getFreeSpace() It returns the number of unallocated bytes in the partition named by this
abstract path name.
String[] It returns an array of strings naming the files and directories in the
list(FilenameFilter directory denoted by this abstract pathname that satisfy the specified
filter) filter.
boolean mkdir() It creates the directory named by this abstract pathname.
boolean It atomically creates a new, empty file named by this abstract pathname
createNewFile() if and only if a file with this name does not yet exist.
Java FileInputStream Class: Java FileInputStream class obtains input bytes from
a file. It is used for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc. You can also read character-stream data. But, for reading
streams of characters, it is recommended to use FileReader class.
Java FileOutputStream Class: Java FileOutputStream is an output stream used
for writing data to a file. If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well as character-oriented
data through FileOutputStream class. But, for character-oriented data, it is
preferred to use FileWriter than FileOutputStream.
Java FileReader Class: Java FileReader class is used to read data from the file. It
returns data in byte format like FileInputStream class. It is character-oriented class
which is used for file handling in java.
Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If file
file) doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If
file doesn't exist, it throws FileNotFoundException.
- 26 -
Java FileWriter Class: Java FileWriter class is used to write character-oriented
data to a file. It is character-oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.
Constructor Description
FileWriter(String file) Creates a new file. It gets file name in string.
FileWriter(File file) Creates a new file. It gets file name in File object.
- 27 -
boolean readBoolean() to read one input byte and return true if byte is non zero,
false if byte is zero.
int skipBytes(int x) to skip over x bytes of data from the input stream.
String readUTF() to read a string that has been encoded using the UTF-8
format.
void readFully(byte[] b) to read bytes from the input stream and store them into the
buffer array.
void readFully(byte[] b, int off, to read len bytes from the input stream.
int len)
int size() It is used to return the number of bytes written to the data
output stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.
len)
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte
value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
- 28 -
ti
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.
SET A
1. Write a java program to accept a number from the user, if number is negative
then throw user defined exception ―Negative number , otherwise check
whether no is prime or not.
2. Write a java program to accept Doctor Name from the user and check
whether it is valid or not. (It should not contain digits and special symbol) If
it is not valid then throw user defined Exception- Name is Invalid--
otherwise display it.
3. 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.
4. Define class EmailId with members ,username and password. Define
default and parameterized constructors. Accept values from the command
line Throw user defined exceptions – “InvalidUsernameException” or
“InvalidPasswordException” if the username and password are invalid
SET B
1. Write a program to copy the contents of one file to another. Copy the
contents in Upper case in second file. Accept two file names using command
line program.
2. Write a program to accept a string as command line argument and check
whether it is a file or directory. Also perform operations as follows:
i. If it is a directory, delete all text files in that directory. Confirm delete
operation from user before deleting text files. Also, display a count
showing the number of files deleted, if any, from the directory.
ii. If it is a file display various details of that file.
3. Write a java program that displays the number of characters, lines and words
of a file.
4. Write a java program to accept details of n customers (c_id, cname, address,
mobile_no) from user and store it in a file (Use DataOutputStream class).
Display the details of customers by reading it from file.(Use
- 29 -
DataInputStream class)
SET C
1. Write a menu driven program to perform the following operations on a set of
integers.
i. Load: This operation should generate 10 random integers (2 digit) and
display the number on screen.
ii. Save: The save operation should save the number to a file “number.txt”.
iii. Exit
Assignment Evaluation
Assignment 5: Swing
- 30 -
Aim: Swing is a part of the Java Foundation Classes (JFC) and provides a rich set
of components for building sophisticated and customizable interfaces.
Theory:
Hierarchy of Java Swing classes: The hierarchy of java swing API is given
below.
- 32 -
JRadioButton Selectable component that displays state to user; included in
ButtonGroup to ensure that only one button is selected.
JRadioButtonMenuIte Selectable component for menus; displays state to user; included in
m ButtonGroup to ensure that only one button is selected.
JRootPane Inner container used by JFrame, JApplet, and others.
JScrollBar For control of a scrollable area.
JScrollPane To provide scrolling support to another component.
JSeparator For placing a separator line on a menu or toolbar.
JSlider For selection from a numeric range of values.
JSpinner For selection from a set of values, from a list, a numeric range, or a
date range.
JSplitPane Container allowing the user to select the amount of space for each of
two components.
JTabbedPane Container allowing for multiple other containers to be displayed;
each container appears on a tab.
JTable For display of tabular data.
JTextArea For editing and display of single-attributed textual content.
JTextField For editing and display of single-attributed textual content on a
single line.
JTextPane For editing and display of multi-attributed textual content.
JToggleButton Selectable component that supports text/image display; selection
triggers component to stay “in”.
JToolBar Draggable container.
JToolTip Internally used for displaying tool tips above components.
JTree For display of hierarchical data.
JViewport Container for holding a component too big for its display area.
JWindow Base class for pop-up windows.
Important Containers:
1.JFrame: This is a top-level container which can hold components and containers
like panels.
Constructors: JFrame(), JFrame(String title)
- 33 -
Methods
Constructor or Method Purpose
JFrame() Creates a frame
JFrame(String title) Creates a frame with title
setSize(int width, int height) Specifies size of the frame in pixels
setSize(int width, int height) Specifies upper left corner
setSize(int width, int height) Set true to display the frame
setTitle(String title) Sets the frame title
setDefaultCloseOperation(int mode) Specifies the operation when frame is closed
JLabel: With the JLabel class, you can display unselectable text and images.
Constructors: JLabel(Icon i), JLabel(Icon I , int n), JLabel(String s), JLabel(String
s, Icon i, int n), JLabel(String s, int n), JLabel()
The int argument specifies the horizontal alignment of the label's contents within
its drawing area; defined in the SwingConstants interface (which JLabel
implements): LEFT (default), CENTER, RIGHT, LEADING, or TRAILING.
Methods: void setText(String), String getText(), void setIcon (Icon), Icon
getIcon(), void setDisabledIcon(Icon), Icon getDisabledIcon(), void
setHorizontalAlignment(int), void setVerticalAlignment(int), int
getHorizontalAlignment(), int getVerticalAlignment()
JButton: 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()
- 36 -
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)
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()
To create a button group- ButtonGroup(), Adds a button to the group, or removes a
button from the group, void add(AbstractButton), void remove(AbstractButton)
JComboBox:
Constructors: JComboBox()
Methods: void addItem(Object), Object getItemAt(int), Object getSelectedItem(),
int getItemCount()
JList:
Constructor: JList(ListModel)
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()
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)
b. JPasswordField:
Constructors: JPasswordField(), JPasswordField(String),
JPasswordField(String, int) , JPasswordField(int), JPasswordField(Document,
String, int)
Methods:
1. Set or get the text displayed by the text field: void setText(String) String
getText()
- 37 -
2. Set or get the text displayed by the text field: char[] getPassword()
3. Set or get whether the user can edit the text in the text field: void
setEditable(boolean) boolean isEditable()
4. Set or get the number of columns displayed by the text field. This is really
just a hint for computing the field's preferred width: void setColumns(int);
5. int getColumns()
6. Get the width of the text field's columns. This value is established implicitly
by the font: int getColumnWidth()
7. Set or get the echo character i.e. the character displayed instead of the
actual characters typed by the user: void setEchoChar(char) char
getEchoChar()
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)
- 38 -
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.
The following table lists the events, their corresponding listeners and the method to
add the listener to the component.
Eve Event Event Listener Method to add listener to
nt Source event source
Low – Level Events
ComponentEve Component ComponentListener addComponentListener()
nt
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
- 39 -
ActionEvent Button List ActionListener addActionListener()
MenuItem
TextField
SET A
1. Write a java program to design a following GUI. Use appropriate Layout and
Components.
2. Write a java program to design a following GUI. Use appropriate Layout and
Components.
- 40 -
3. Write a program to design following GUI using JTextArea. Write a code to
display number of words and characters of text in JLabel. Use JScrollPane to
get scrollbars for JTextArea.
- 41 -
4. Write a Program to design following GUI by using swing component
JComboBox. On click of show button display the selected language on JLabel.
SET B
1. Implement event handling for SET A 1. Verify username and password in 3
attempts. Display dialog box "Login successful" on success or display
"Username or Password is in correct". After 3 attempts display "Login Failed".
On reset button clear the fields of text box.
2. Implement event handling for SET A 2. Display selected Name, Vaccine. If 1st
Dose is taken then write Yes otherwise write No.
3. Write a java program to create the following GUI using Swing components.
- 42 -
SET C
1. Write a program to design and implement following GUI.
- 43 -
Signature of instructor: ________________________ Date: _________________
Assignment Evaluation
- 44 -