0% found this document useful (0 votes)
6 views134 pages

Java Unit-1 Revision

The document outlines the curriculum for an Advance Java Programming course, covering topics such as Core Java, Swing Framework, Object-Oriented Programming concepts like inheritance, polymorphism, encapsulation, and exception handling. It provides detailed explanations of classes, objects, constructors, and various Java keywords, along with examples of exception handling and common scenarios for exceptions. The course is designed for MCA 1st Year students and includes practical applications of Java programming principles.

Uploaded by

Ravi Shankar Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views134 pages

Java Unit-1 Revision

The document outlines the curriculum for an Advance Java Programming course, covering topics such as Core Java, Swing Framework, Object-Oriented Programming concepts like inheritance, polymorphism, encapsulation, and exception handling. It provides detailed explanations of classes, objects, constructors, and various Java keywords, along with examples of exception handling and common scenarios for exceptions. The course is designed for MCA 1st Year students and includes practical applications of Java programming principles.

Uploaded by

Ravi Shankar Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 134

Subject Title: Advance Java Programming,

Code: CAN604, Credit: 3:0:1:4


Class: MCA. 1st Year, 2nd Sem

Unit I: Basics of Core Java and Swing Framework

• Objects and Classes, Inheritance and Polymorphism, Exception Handling,


Interface and Abstract Classes

• GUI basics, Introduction to Swing Framework, Swing Components, Event


Handling, Action Listener, Layout Managers.

DIT University, 17July2019


Classes and Objects
• A class is a blue print from which individual objects are created.
• A class can contain any of the following variable types.
1. Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
2. Instance variables: Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
3. Class variables: Class variables are variables declared with in a class, outside
any method, with the static keyword.
Objects
• An object is any entity that has a state and behavior. For example, a bicycle is an
object. It has
• States: idle, first gear, etc
• Behaviors: braking, accelerating, etc.

Constructors: When discussing about classes, one of the most important sub topic
would be constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.
• Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor. Example of a constructor is given
below:
Creating an Object
• A class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new
objects. There are three steps when creating an object from a class:
1. Declaration: A variable declaration with a variable name with an
object type. Instantiation: The 'new' key word is used to create the
object.
2. Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object. Example of creating
an object is given below:
Revising Concepts
• Inheritance – Inheritance types- super keyword- preventing
inheritance: final classes and methods
• Polymorphism – method overloading and method overriding,
abstract classes and methods.
• Interface – Interfaces VS Abstract classes- defining an interface-
implement interfaces- accessing implementations through interface
references- extending interface -inner classes.
• Packages – Defining- creating and accessing a package- importing
packages.
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
• The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
• The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.
Example:
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported
through interface only.
Why multiple inheritance is not
supported in java?
• To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method and
you call it from child class object, there will be ambiguity to call the
method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Polymorphism
• Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
Method Overloading
• If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
• If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Advantage of method overloading
• Method overloading increases the readability of the program.
• Different ways to overload the method
There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Method Overloading: changing no.
of arguments
• In this example, we have created two methods, first add() method
performs addition of two numbers and second add method performs
addition of three numbers.
Method Overloading: changing data
type of arguments
Method Overriding in Java
• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Difference between method
overloading and method overriding
in java
Super Keyword
• The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference
variable.
Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
• super is used to refer immediate parent class
instance variable.
• We can use super keyword to access the data
member or field of parent class. It is used if
parent class and child class have same fields.
Super can be used to refer immediate Super can be used to invoke parent
parent class instance variable. class method
Final Keyword
• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• variable
• method
• class
• The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block
only. We will have detailed learning of these.
• 1) Java final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).
• Example of final variable
• There is a final variable speedlimit, we are going to change the value
of this variable, but It can't be changed because final variable once
assigned a value can never be changed.
2) Java final method
• If you make any method as final, you cannot override it.
• Example of final method
3) Java final class
• If you make any class as final, you cannot extend it.
• Example of final class
Abstraction
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and send
the message. You don't know the internal processing about the message
delivery.
• Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
• A class which is declared as abstract is known as an abstract class. It
can have abstract and non-abstract methods. It needs to be extended
and its method implemented. It cannot be instantiated.
Example of Abstract class that has
an abstract method
Interface
• An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Why use Java interface?
• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Interface Declaraction:
The relationship between classes
and interfaces
• As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.
Example 1:
Example 2:
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an
interface extends multiple interfaces, it is known
as multiple inheritance.
Encapsulation
• Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
• We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter
methods to set and get the data in it.
• The Java Bean class is the example of a fully encapsulated class.
Example of Encapsulation
Exception example:
Exception Handling
• Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
How an exception is handled?
• We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number.
Exception
• Exception is an unwanted or unexpected event, which occurs during
the execution of a program, i.e. at run time, that disrupts the normal
flow of the program’s instructions. Exceptions can be caught and
handled by the program.
• When an exception occurs within a method, it creates an object. This
object is called the exception object. It contains information about
the exception, such as the name and description of the exception and
the state of the program when the exception occurred.
How Does JVM Handle an
Exception?
• Whenever inside a method, if an exception has occurred, the method creates an
Object known as an Exception Object and hands it off to the run-time system(JVM).
• The exception object contains the name and description of the exception and the
current state of the program where the exception has occurred.
• Creating the Exception Object and handling it in the run-time system is called
throwing an Exception. JVM is responsible for finding an exception handler tp
process the exception object.
• There might be a list of the methods that had been called to get to the method
where an exception occurred. This ordered list of methods is called Call Stack.
• The run-time system searches the call stack to find the method that contains a
block of code that can handle the occurred exception. The block of the code is
called an Exception handler.
1. Built-in Exceptions
• Built-in exceptions are the exceptions that are available in Java libraries.
• Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by
the compiler.

• Unchecked Exceptions: The unchecked exceptions are just opposite to


the checked exceptions. The compiler will not check these exceptions
at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program
would not give a compilation error.
Exception Types
• All Exceptions are subclass of built-in class Throwable.
• Under the hierarchy, 2 subclasses partition exception into 2 distinct
branches.
• 1)Exception-This class is used for exceptional conditions that user
programs should catch. This is also the class which you will subclass to
create your custom exception types.
• There is an important subclass of exception called Runtime Exception
• 2)Error-These are used by java runtime system to indicate errors
related with run time environment.
• Ex-Stack overflow
Exception Handling
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
• What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
• What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Advantage of Exception Handling
• The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:
Hierarchy of Java Exception classes
• The java.lang.Throwable class is the root class of Java Exception
hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:
Java Exception Keywords
• Java provides five keywords that are used to handle the exception.
The following table describes each.
Exception Handling Example
• Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
In the above example, 100/0 raises an
ArithmeticException which is handled by a try-
Common Scenarios of Java
Exceptions
There are given some scenarios where unchecked exceptions may occur. They
are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result
into NumberFormatException. Suppose we have a string variable that
has characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
1) try-catch block
• Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
• If an exception occurs at the particular statement in the try block, the
rest of the block code will not execute. So, it is recommended not to
keep the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
• Syntax of Java try-catch
• try{
• //code that may throw an exception
• }catch(Exception_class_Name ref){}
• Syntax of try-finally block
• try{
• //code that may throw an exception
• }finally{}
• Java catch block is used to handle the Exception by declaring the type
of exception within the parameter. The declared exception must be
the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
• The JVM firstly checks whether the exception is handled or not. If
exception is not handled, JVM provides a default exception handler
that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception
occurred).
• Causes the program to terminate.
• But if the application programmer handles the exception, the normal
flow of the application is maintained, i.e., rest of the code is executed.
Method Call Stack
Stack trace
public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

}
throw keyword
• Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by
throw keyword. It is mainly used to throw a custom exception.
Throwing an Exception
throws keyword

• throws keyword is used to declare an exception.


• It gives an information to the programmer that there may occur an
exception. So, it is better for the programmer to provide the exception
handling code so that the normal flow of the program can be
maintained.
• Syntax
Java AWT (Abstract Window Toolkit)
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical
User Interface (GUI) or windows-based applications in Java.
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. AWT is heavy
weight i.e. its components are using the resources of underlying
operating system (OS).
• The java.awt package provides classes for AWT API such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Why AWT is platform dependent?
• Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField,
ChechBox, button, etc.
• For example, an AWT GUI with components like TextField, label and
button will have different look and feel for the different platforms like
Windows, MAC OS, and Unix. The reason for this is the platforms have
different view for their native components and AWT directly calls the
native subroutine that creates those components.
• In simple words, an AWT application will look like a windows application
in Windows OS whereas it will look like a Mac application in the MAC
OS.
Java AWT Hierarchy
Components
• All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as
shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
Container
• The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc. The classes that
extends Container class are known as container such as Frame,
Dialog and Panel.
• It is basically a screen where the where the components are placed at
their specific locations. Thus it contains and controls the layout of
components.
Types of containers:
• There are four types of containers in Java AWT:
• Window
• Panel
• Frame
• Dialog
Window
• The window is the container that have no borders and menu bars. You
must use frame, dialog or another window for creating a window. We
need to create an instance of Window class to create this container.
Panel
• The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates
a container, in which we can add components.
Frame
• The Frame is the container that contain title bar and border and can
have menu bars. It can have other components like button, text field,
scrollbar etc. Frame is most widely used container while developing an
AWT application.
Applets(Lets get started)
• Applets are small Java applications which can be accessed on an Internet
server, transported over the Internet, and can be installed and run
automatically as part of a web document.
• The applet can create a graphical user interface after a user gets an applet. It
has restricted access to resources so that complicated computations can be
carried out without adding the danger of viruses or infringing data integrity.
• Any Java applet is a class that extends the class of java.applet.Applet.
• There is no main() methods in an Applet class. Using JVM it is regarded. The
JVM can operate an applet application using either a Web browser plug-in or
a distinct runtime environment.
• JVM generates an applet class instant and invokes init() to initialize an
applet.
Benefits of Applets
• As it operates on the client side, it requires much less response time.
• Any browser that has JVM operating in it can operate it.
Applet class
• Applet class provides all the support needed to execute applets, such
as initializing and destroying applets. It also provides
techniques/methods for loading and displaying audio videos and
playback pictures.
Lifecycle of an Applet
1)Initialization- public void init(),
The first technique to be called is init(). This is where you initialize the variable. This technique is only
called once during the applet runtime.
2)Start- public void start(),
Method start() is called after ini(). This technique is called after it has been stopped to restart an
applet.
Executed when browser is maximized.
3)Paint- public void paint(Graphics g),
4)Stop- public void stop()-Executed when browser is minimized.
Method stop() is called to suspend threads that do not need to operate when the applet is not
noticeable.
5)Destroy- public void destroy()
The destroy() technique/method is called if you need to remove your applet from memory entirely.
Executed when browser is closed.
Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
Simple Applet
An Applet Skelton
AWT UI Components
• Component class
Component class is at the top of AWT hierarchy. It is an abstract class
that encapsulates all the attributes of visual component. A component
object is responsible for remembering the current foreground and
background colors and the currently selected text font.
• Container
Container is a component in AWT that contains another component
like button, text field, tables etc. Container is a subclass of component
class. Container class keeps track of components that are added to
another component.
• Panel
Panel class is a concrete subclass of Container. Panel does not contain
title bar, menu bar or border. It is container that is used for holding
components.
• Window class
Window class creates a top level window. Window does not have
borders and menubar.
• Frame
Frame is a subclass of Window and have resizing canvas. It is a
container that contain several different components like button, title
bar, textfield, label etc. In Java, most of the AWT applications are
created using Frame window. Frame class has two different
constructors,
Useful Methods of Component Class
To create simple AWT example, you need a frame. There are two ways
to create a GUI using Frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
By extending Frame class (inheritance)
By creating the object of Frame class (association)
AWT Button
• In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
• create a button and it to the frame by providing coordinates.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
• In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is allowed and the text
can not be changed directly.
• creating two labels to display text to the frame.
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
AWT TextField
• WT contains aTextField Class. It is used for displaying single line text.
• creating two textfields to display single line text string.
import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
AWT TextArea
• AWT contains aTextArea Class. It is used for displaying multiple-line text.
• creating a TextArea that is used to display multiple-line text string and allows text editing as well.

import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
AWT Checkbox
• AWT contains a Checkbox Class. It is used when we want to select
only one option i.e true or false. When the checkbox is checked then
its state is "on" (true) else it is "off"(false).
• creating checkbox that are used to get user input. If checkbox is
checked it returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
AWT Choice
• AWT contains a Choice Class. It is used for creating a drop-down menu
of choices. When a user selects a particular item from the drop-down
then it is shown on the top of the menu.
• creating drop-down menu that is used to get user choice from
multiple choices.
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
AWT List
• AWT contains a List Class. It is used to represent a list of items
together. One or more than one item can be selected from the list.
• creating a list that is used to list out the items.
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
Swings
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used
to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight
components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
• Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT]. Swing offers much-improved
functionality over AWT, new components, expanded components
features, and excellent event handling with drag-and-drop support.
Introduction to Swing framework
• Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class)
helpful in developing window-based applications.
• Java Swing is lightweight and platform-independent that contains
various components and container classes.
• Furthermore, the Java swing library is built on the top of the
AWT(Abstract Window Toolkit), an API completely written in Java.
• In every application, users can find an interactive and user-friendly
interface that gives them the freedom to use the app.
Swing Components
• Swing components are the fundamental building blocks of an
application. Swing has various components, including buttons,
checkboxes, sliders, and list boxes. In this part of the Swing tutorial,
we will present JButton, JLabel, JTextField, and JPasswordField.
function of Swing components in Java
• Swing in java is part of the Java foundation class, which is lightweight
and platform-independent. It is used for creating window-based
applications.
Difference between Swing and
AWT components
Swing and AWT are the two toolkits for building interactive Graphical
User Interfaces (GUI).
The critical difference between Swing and AWT in Java is that AWT is
Java's conventional platform-dependent graphics and user interface
widget toolkit. In contrast, Swing is a GUI widget toolkit for Java, an
AWT extension.
Hierarchy of Java Swing classes
Example 1: Develop a program using label
(swing) to display message “Java is Amazing”;

import java.io.*;
import javax.swing.*;
class ABC {
public static void main(String[] args)
{
JFrame frame= new JFrame();
JButton button = new JButton(" Java is Amazing");
button.setBounds(150, 200, 220,50);
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
}
}
Example 2: Write a program to create three
buttons with caption OK , SUBMIT, CANCLE.
import java.awt.*;
class button {
button() {
Frame f = new Frame();
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
Button b3 = new Button("CANCLE");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String a[]) {
new button();
}
}
SWING UI Elements
Swing Features
• Light Weight − Swing components are independent of native
Operating System's API as Swing API controls are rendered mostly
using pure JAVA code instead of underlying operating system calls.
• Rich Controls − Swing provides a rich set of advanced controls like
Tree, TabbedPane, slider, colorpicker, and table controls.
• Highly Customizable − Swing controls can be customized in a very
easy way as visual apperance is independent of internal
representation.
• Pluggable look-and-feel − SWING based GUI Application look and feel
can be changed at run-time, based on available values.
Java Jframe:
• The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with
the help of setDefaultCloseOperation(int) method.
setDefaultCloseOperation():

The setDefaultCloseOperation() method is used to specify one of several options for the
close button. Use one of the following constants to specify your choice:

 JFrame.EXIT_ON_CLOSE — Exit the application.


 JFrame.HIDE_ON_CLOSE — Hide the frame, but keep the application running. (By Default)
 JFrame.DISPOSE_ON_CLOSE — Dispose of the frame object, but keep the application running.
 JFrame.DO_NOTHING_ON_CLOSE — Ignore the click.
Event Handling
• An event can be defined as changing the state change of an object or
behavior by performing actions. Actions can be a button click, cursor
movement, keypress through keyboard or page scrolling, etc.
• Classification of Events
• Foreground Events
• Background Events
• 1. Foreground Events
• Foreground events are the events that require user interaction to
generate, i.e., foreground events are generated due to interaction by
the user on components in Graphic User Interface (GUI). Interactions
are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
• 2. Background Events
• Events that don’t require interactions of users to generate are known
as background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling
• It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows
the Delegation Event model.
• Delegation Event model
• It has Event Sources and Event Listeners.
Event Handling: The Delegation
Event Model
• The delegation event model, which defines standard and consistent
mechanisms to generate and process events. Its concept is quite simple: a
source generates an event and sends it to one or more listeners. In this
scheme, the listener simply waits until it receives an event. Once
received, the listener processes the event and then returns. The
advantage of this design is that the application logic that processes events
is cleanly separated from the user interface logic that generates those
events.
• In the delegation event model, listeners must register with a source in
order to receive an event notification. This provides an important benefit:
notifications are sent only to listeners that want to receive them.
Events:
• In the delegation model, an event is an object that describes a state
change in a source. It can be generated as a consequence of a person
interacting with the elements in a graphical user interface. Some of
the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and
clicking the mouse. Events may also occur that are not directly caused
by interactions with a user interface.
• For example, an event may be generated when a timer expires, a
counter exceeds a value, a software or hardware failure occurs, or an
operation is completed.
Event Sources:
• A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than
one type of event. A source must register listeners in order for the listeners to
receive notifications about a specific type of event. Each type of event has its
own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
• Here, Type is the name of the event and el is a reference to the event listener.
• A source must also provide a method that allows a listener to unregister an
interest in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
Event Listeners:
• A listener is an object that is notified when an event occurs.
• It has two major requirements:
• First, it must have been registered with one or more sources to
receive notifications about specific types of events.
• Second, it must implement methods to receive and process these
notifications. The methods that receive and process events are
defined in a set of interfaces found in java.awt.event.
Event Classes in Java
• Different interfaces consists of different methods which are specified
below.
Flow of Event Handling

1.User Interaction with a component is required to generate an event.

2.The object of the respective event class is created automatically


after event generation, and it holds all information of the event source.

3.The newly created object is passed to the methods of the registered


listener.

4.The method executes and returns the result.


The ActionEvent Class:
• An ActionEvent is generated when a button is pressed, a list item is
double-clicked,or a menu item is selected.
• Used to handle events caused by sources like button, menuitems ets.
• Override public void actionPerformed(ActionEvent e)
Action Listener Interface
• The ActionListener Interface: This interface defines the
actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
Handling Buttons:
• Each time a button is pressed,an ActionEvent is generated. This is sent
to any listeners that previously registered an interest in receiving
action event notifications from that component. Each listener
implements the ActionListener interface. That interface defines the
actionPerformed( ) method, which is called when an event occurs. An
ActionEvent object is supplied as the argument to this method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EventExample extends JFrame implements ActionListener
{
private int count =0;
JLabel lblData;
EventExample()
{
setLayout(new FlowLayout());
lblData = new JLabel("Button Clicked 0 Times");
JButton btnClick=new JButton("Click Me");
btnClick.addActionListener(this);
add(lblData);
add(btnClick);
}
public void actionPerformed(ActionEvent e)
{
count++;
lblData.setText("Button Clicked " + count +" Times");
}
}
class EventHandlingJavaExample
{
public static void main(String args[])
{
EventExample frame = new EventExample();
frame.setTitle("Event Handling Java Example");
frame.setBounds(200,150,180,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
To write an Action Listener, follow
the steps given below:
1) Declare an event handler class and specify that the class either implements an
ActionListener interface or extends a class that implements an ActionListener
interface.
For example:
Ex- public class MyClass implements ActionListener {
2) Register an instance of the event handler class as a listener on one or more
components.
Ex- someComponent.addActionListener(instanceOfMyClass);
3) Include code that implements the methods in listener interface.
For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
Import java.awt.*;
Import java.awt.event.*;
Class eventExample extends Frame implements ActionListener{
eventExample(){
Frame f=new Frame(“Test”);
Button b =new Button(“click”);
Textfield t=new TextField”10);

f.add(b);
f.add(t);

b.addActionListener(this); Registration
}
Public void actionPerformed(ActionEvent ae){
String s=ae.getActionCommand();
t.setText(s);
}
Public static void main(String[] args){
eventExample ex=new eventExample();
}
ItemListener
• Used for radioButton, List,Choice, and Checkbox.
• Override public void itemStateChanged(ItemEvent e)

Checkbox c1=new Checkbox(“subject”,false);


C1.addItemListener(this);
Public void itemstatechanged(ItemEvent e)
{
If(c1.getState()){ //true if C1 is selected

}
}
Example: WAP to create a frame. Place 3 buttons: yes, no , maybe
and prints a message for the same using ActionEvent.
Practice Q1:Print message on button
ActionEvent
Practice Q2:Basic Calculator
Layout Managers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of layout
managers.
• The layout manager automatically positions all the components within the
container. Even if you do not use the layout manager, the components are still
positioned by the default layout manager.
• Java provides various layout managers to position the controls. Properties like
size, shape, and arrangement varies from one layout manager to the other.
When the size of the applet or the application window changes, the size,
shape, and arrangement of the components also changes in response, i.e. the
layout managers adapt to the dimensions of the appletviewer or the
application window.
There are the following classes that
represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout
Java BorderLayout Class
• The BorderLayout is used to arrange the components in five regions:
north, south, east, west, and center. Each region (area) may contain
one component only. It is the default layout of a frame or window.
• The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
• BorderLayout(): creates a border layout but with no gaps between the
components.
Example of BorderLayout class: Using BorderLayout() constructor

You might also like