Unit 1 Notes PPT.pptxUnit-3_updated.pptxUnit-3_updated.pptx

mememintra783 0 views 116 slides Oct 07, 2025
Slide 1
Slide 1 of 116
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116

About This Presentation

gfvnjhgbm, jb nmUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptxUnit-3_updated.pptx


Slide Content

Subject Title: Advance Java Programming, Code: CSF206 , Credit: 3:0:1:4 Class: B.Tech . 2 st Year, 4 th 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. 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. 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. 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: Declaration: A variable declaration with a variable name with an object type. Instantiation: The 'new' key word is used to create the object. 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 parent class instance variable. Super can be used to invoke parent 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 Abstract class (0 to 100%) 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

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 for drawing oval, rectangle, arc etc.

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.

Difference between Swing and AWT components Java AWT Java Swing Java AWT is an API to develop GUI applications in Java. Swing is a part of Java Foundation Classes and is used to create various applications. Components of AWT are heavy weighted. The components of Java Swing are lightweight. Components are platform dependent. Components are platform independent. Execution Time is more than Swing. Execution Time is less than AWT. AWT components require java.awt package.  Swing components requires javax.swing package.

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 (" GFG WebSite Click"); 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 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. The following sections define events and describe the roles of sources and listeners

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. Many other user operations could also be cited as examples. 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. You are free to define events that are appropriate for your application.

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 User Interaction with a component is required to generate an event. The object of the respective event class is created automatically after event generation, and it holds all information of the event source. The newly created object is passed to the methods of the registered listener. 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. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK,CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED , which can be used to identify action events. ActionEvent has these three constructors: ActionEvent (Object src , int type, String cmd ) ActionEvent (Object src , int type, String cmd , int modifiers) ActionEvent (Object src , int type, String cmd , long when, int modifiers) Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd.

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.

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: java.awt.BorderLayout java.awt.FlowLayout java.awt.GridLayout java.awt.CardLayout java.awt.GridBagLayout javax.swing.BoxLayout javax.swing.GroupLayout javax.swing.ScrollPaneLayout javax.swing.SpringLayout etc.

import javax . swing .*; import java . awt .*; import java . awt . event .*; class EventExample extends JFrame implements ActionListener {     private int count = ;     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 );     }   }

Exceptions Java Exception is an object that describes exceptional condition occurred in a piece of code. When an Exception condition arises- Object representing that exception is created and thrown in the method that caused the exception. That method may chose to handle the exception or pass it on. Exceptions are generated by java runtime system or they can be manually generated by your code. Java exceptions handling is managed via five keywords: Try, catch, throw, throws, finally.

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:

Types of Java Exceptions There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely: Checked Exception Unchecked Exception Error

Checked and Unchecked Exceptions 1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error, are known as checked exceptions. For example, IOException , SQLException , etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException , etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error Error is irrecoverable. Some example of errors are OutOfMemoryError , VirtualMachineError , AssertionError etc.

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-catch block.

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.

public   class  TryCatchExample1 {           public   static   void  main(String[]  args ) {                       int  data=50/0; //may throw exception                        System.out.println ("rest of the code");                  }          }  
Tags