UNIT 3 Event and GUI Programming in Java
UNIT 3 Event and GUI Programming in Java
Boxes, Lists, Scroll Bars, Sliders, Windows, Menus, 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
Dialog Box, Applet and its life cycle, Introduction to
that creates those components.
swing, Exceptional handling mechanism.
In simple words, an AWT application will look like a windows application in
Java AWT Windows OS whereas it will look like a Mac application in the MAC OS.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 1
Java AWT Hierarchy 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:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must
Components use frame, dialog or another window for creating a window. We need to
create an instance of Window class to create this container.
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 Panel
in above diagram. In order to place every component in a particular position
on a screen, we need to add them to a container. 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 container, in which we can add components.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 2
Frame Let's see a simple example of AWT where we are inheriting Frame class.
Here, we are showing Button component on the 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 AWTExample1.java
etc. Frame is most widely used container while developing an AWT // importing Java AWT class
application. import java.awt.*;
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 3
class AWTExample2 {
// creating instance of Frame class
AWTExample1 f = new AWTExample1(); // initializing using constructor
AWTExample2() {
}
// creating a Frame
} Frame f = new Frame();
The setBounds(int x-axis, int y-axis, int width, int height) method is used in // creating a Label
the above example that sets the position of the awt button. Label l = new Label("Employee id:");
// creating a TextField
TextField t = new TextField();
Let's see a simple example of AWT where we are creating instance of Frame // frame size 300 width and 300 height
class. Here, we are creating a TextField, Label and Button component on the f.setSize(400,300);
Frame.
// setting the title of frame
AWTExample2.java f.setTitle("Employee info");
// class AWTExample2 directly creates instance of Frame class // setting visibility of frame
f.setVisible(true);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 4
}
MouseWheelEvent MouseWheelListener
// main method
public static void main(String args[]) { KeyEvent KeyListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 5
public void addActionListener(ActionListener a){} Anonymous class
Other class
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 6
public void setBounds(int xaxis, int yaxis, int width, int height); have been }
used in the above example that sets the position of the component it may }
be button, textfield etc. import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
2) Java event handling by outer class
3) Java event handling by anonymous class
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
class AEvent2 extends Frame{ class AEvent3 extends Frame{
TextField tf; TextField tf;
AEvent2(){ AEvent3(){
//create components tf=new TextField();
tf=new TextField(); tf.setBounds(60,50,170,20);
tf.setBounds(60,50,170,20); Button b=new Button("click me");
Button b=new Button("click me"); b.setBounds(50,120,80,30);
b.setBounds(100,120,80,30);
//register listener b.addActionListener(new ActionListener(){
Outer o=new Outer(this); public void actionPerformed(){
b.addActionListener(o);//passing outer class instance tf.setText("hello");
//add components and set size, layout and visibility }
add(b);add(tf); });
setSize(300,300); add(b);add(tf);
setLayout(null); setSize(300,300);
setVisible(true); setLayout(null);
} setVisible(true);
public static void main(String args[]){ }
new AEvent2();
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 7
public static void main(String args[]){
new AEvent3(); Sr. no. Constructor Description
}
} 1. Button( ) It constructs a new button with an empty string
i.e. it has no label.
Java AWT Button 2. Button (String It constructs a new button with given string as its
text) label.
A button is basically a control component with a label that generates an
event when pushed. The Button class is used to create a labeled button that
has platform independent implementation. The application result in some
Button Class Methods
action when the button is pushed.
Sr. Method Description
When we press a button and release it, AWT sends an instance
no.
of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then it
1. void setText (String It sets the string message on the button
passes an action event by calling its own method processActionEvent. This
text)
method passes the action event on to action listeners that are interested in
the action events generated by the button. 2. String getText() It fetches the String message on the button.
To perform an action on a button being pressed and released, 3. void setLabel It sets the label of button with the specified
the ActionListener interface needs to be implemented. The registered new (String label) string.
listener can receive events from the button by
calling addActionListener method of the button. The Java application can 4. String getLabel() It fetches the label of the button.
use the button's action command as a messaging protocol.
5. void addNotify() It creates the peer of the button.
AWT Button Class Declaration 6. AccessibleContext It fetched the accessible context associated
getAccessibleCont with the button.
public class Button extends Component implements Accessible ext()
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 8
8. String It returns the command name of the action Example 1:
getActionComman event fired by the button.
d() ButtonExample.java
10. T[ ] It returns an array of all the objects currently // create instance of frame with the label
getListeners(Class l registered as FooListeners upon this Button. Frame f = new Frame("Button Example");
istenerType)
// create instance of button with label
11. protected String It returns the string which represents the state Button b = new Button("Click Here");
paramString() of button.
// set the position for the button in frame
12. protected void It process the action events on the button by b.setBounds(50,100,80,30);
processActionEven dispatching them to a registered ActionListener
t (ActionEvent e) object. // add button to the frame
f.add(b);
13. protected void It process the events on the button // set size, layout and visibility of frame
processEvent f.setSize(400,400);
(AWTEvent e) f.setLayout(null);
f.setVisible(true);
14. void It removes the specified action listener so that
}
removeActionListe it no longer receives action events from the
}
ner (ActionListener button.
l)
To compile the program using command prompt type the following
15. void It sets the command name for the action event commands
setActionComman given by the button.
d(String command) C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 9
public static void main (String args[])
{
new ButtonExample2();
}
}
Output:
Example 2:
// importing necessary libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 10
// create instance of button with label When we enter a key in the text field (like key pressed, key released or key
Button b=new Button("Click Here"); typed), the event is sent to TextField. Then the KeyEvent is passed to the
// set the position for the button in frame registered KeyListener. It can also be done using ActionEvent; if the
b.setBounds(50,100,60,30); ActionEvent is enabled on the text field, then the ActionEvent may be fired
b.addActionListener(new ActionListener() {
by pressing return key. The event is handled by the ActionListener interface.
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Java.");
} AWT TextField Class Declaration
});
// adding button the frame
public class TextField extends TextComponent
f.add(b);
// adding textfield the frame
f.add(tf); TextField Class constructors
// setting size, layout and visibility
f.setSize(400,400);
f.setLayout(null); Sr. Constructor Description
f.setVisible(true); no.
}
}
1. TextField() It constructs a new text field component.
Output:
2. TextField(String It constructs a new text field initialized with
text) the given string text to be displayed.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 11
Sr. Method name Description 10. Dimension It fetches the preferred size of the text
no getPreferredSize() field.
.
11. Dimension It fetches the preferred size of the text field
getPreferredSize(int with specified number of columns.
1. void addNotify() It creates the peer of text field. columns)
2. boolean It tells whether text field has character set 12. protected String It returns a string representing state of the
echoCharIsSet() for echoing or not. paramString() text field.
3. void It adds the specified action listener to 13. protected void It processes action events occurring in the
addActionListener( receive action events from the text field. processActionEvent text field by dispatching them to a
ActionListener l) (ActionEvent e) registered ActionListener object.
4. ActionListener[] It returns array of all action listeners 14. protected void It processes the event on text field.
getActionListeners() registered on text field. processEvent(AWTE
vent e)
5. AccessibleContext It fetches the accessible context related to
getAccessibleConte the text field. 15. void It removes specified action listener so that
xt() removeActionListen it doesn't receive action events anymore.
er(ActionListener l)
6. int getColumns() It fetches the number of columns in text
field. 16. void setColumns(int It sets the number of columns in text field.
columns)
7. char getEchoChar() It fetches the character that is used for
echoing. 17. void It sets the echo character for text field.
setEchoChar(char c)
8. Dimension It fetches the minimum dimensions for the
getMinimumSize() text field. 18. void setText(String It sets the text presented by this text
t) component to the specified text.
9. Dimension It fetches the minimum dimensions for the
getMinimumSize(in text field with specified number of
t columns) columns. Method Inherited
The AWT TextField class inherits the methods from below classes:
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 12
java.awt.TextComponent Output:
java.awt.Component
java.lang.Object
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 13
tf3 = new TextField(); }
tf3.setBounds(50, 150, 150, 20); String result = String.valueOf(c);
tf3.setEditable(false); tf3.setText(result);
b1 = new Button("+"); }
b1.setBounds(50, 200, 50, 50); // main method
b2 = new Button("-"); public static void main(String[] args) {
b2.setBounds(120,200,50,50); new TextFieldExample2();
// adding action listener }
b1.addActionListener(this); }
b2.addActionListener(this); Output:
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on button
s
public void actionPerformed(ActionEvent e) {
Java AWT TextArea
String s1 = tf1.getText();
The object of a TextArea class is a multiline region that displays text. It allows
String s2 = tf2.getText();
the editing of multiple line text. It inherits TextComponent class.
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
The text area allows us to type as much text as we want. When the text in
int c = 0;
the text area becomes larger than the viewable area, the scroll bar appears
if (e.getSource() == b1){
automatically which helps us to scroll the text up and down, or right and left.
c = a + b;
}
else if (e.getSource() == b2){ AWT TextArea Class Declaration
c = a - b;
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 14
public class TextArea extends TextComponent
4. TextArea (String text, It constructs a new text area with the
int row, int column) specified text in the text area and
Fields of TextArea Class specified number of rows and columns.
The fields of java.awt.TextArea class are as follows: 5. TextArea (String text, It construcst a new text area with
int row, int column, int specified text in text area and specified
static int SCROLLBARS_BOTH - It creates and displays both horizontal and scrollbars) number of rows and columns and
vertical scrollbars. visibility.
java.lang.Object
Class constructors:
TetArea Class Methods
Sr. Constructor Description
no.
Sr. Method name Description
1. TextArea() It constructs a new and empty text area no.
with no text in it.
1. void addNotify() It creates a peer of text area.
2. TextArea (int row, int It constructs a new text area with
column) specified number of rows and columns 2. void append(String str) It appends the specified text to the
and empty string as text. current text of text area.
3. TextArea (String text) It constructs a new text area and 3. AccessibleContext It returns the accessible context
displays the specified text in it. getAccessibleContext() related to the text area
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 15
4. int getColumns() It returns the number of columns of 14. void setColumns(int It sets the number of columns for
text area. columns) this text area.
5. Dimension It determines the minimum size of 15. void setRows(int rows) It sets the number of rows for this
getMinimumSize() a text area. text area.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 16
// main method public class TextAreaExample2 extends Frame implements ActionListener
public static void main(String args[]) {
{ // creating objects of Label, TextArea and Button class.
new TextAreaExample(); Label l1, l2;
} TextArea area;
} Button b;
Output: // constructor to instantiate
TextAreaExample2() {
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 17
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
Checkbox Class Constructors
l2.setText("Characters: "+text.length());
} Sr. Constructor Description
// main method no.
public static void main(String[] args) {
new TextAreaExample2();
1. Checkbox() It constructs a checkbox with no string
}
as the label.
}
Output: 2. Checkbox(String label) It constructs a checkbox with the given
label.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 18
Sr. Method name Description 11. protected void It processes the event on checkbox.
no processEvent(AWTEvent
e)
.
12. protected void It process the item events occurring
1. void It adds the given item listener to get processItemEvent(ItemEv in the checkbox by dispatching them
addItemListener(ItemList the item events from the checkbox. ent e) to registered ItemListener object.
ener IL)
13. void It removes the specified item listener
2. AccessibleContext It fetches the accessible context of removeItemListener(Item so that the item listener doesn't
getAccessibleContext() checkbox. Listener l) receive item events from the
checkbox anymore.
3. void addNotify() It creates the peer of checkbox.
14. void It sets the checkbox's group to the
4. CheckboxGroup It determines the group of checkbox.
setCheckboxGroup(Check given checkbox.
getCheckboxGroup()
boxGroup g)
5. ItemListener[] It returns an array of the item
15. void setLabel(String label) It sets the checkbox's label to the
getItemListeners() listeners registered on checkbox.
string argument.
6. String getLabel() It fetched the label of checkbox.
16. void setState(boolean It sets the state of checkbox to the
state) specified state.
7. T[] It returns an array of all the objects
getListeners(Class listener registered as FooListeners.
Type) Java AWT Checkbox Example
8. Object[] It returns an array (size 1) containing
getSelectedObjects() checkbox label and returns null if In the following example we are creating two checkboxes using the
checkbox is not selected. Checkbox(String label) constructo and adding them into the Frame using
add() method.
9. boolean getState() It returns true if the checkbox is on,
else returns off. CheckboxExample1.java
// importing AWT class
10. protected String It returns a string representing the import java.awt.*;
paramString() state of checkbox. public class CheckboxExample1
{
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 19
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1); Java AWT Checkbox Example with ItemListener
f.add(checkbox2);
In the following example, we have created two checkboxes and adding them
// setting size, layout and visibility of frame into the Frame. Here, we are adding the ItemListener with the checkbox
f.setSize(400,400); which displays the state of the checkbox (whether it is checked or
f.setLayout(null); unchecked) using the getStateChange() method.
f.setVisible(true);
} CheckboxExample2.java
// main method // importing necessary packages
public static void main (String args[]) import java.awt.*;
{ import java.awt.event.*;
new CheckboxExample1(); public class CheckboxExample2
} {
} // constructor to initialize
Output: CheckboxExample2() {
// creating the frame
Frame f = new Frame ("CheckBox Example");
// creating the label
final Label label = new Label();
// setting the alignment, size of label
label.setAlignment(Label.CENTER);
label.setSize(400,100);
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 20
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
// adding the checkbox to frame
f.add(checkbox1);
f.add(checkbox2);
f.add(label);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 21
CheckboxGroup cbg = new CheckboxGroup(); public class CheckboxGroupExample
Checkbox checkBox1 = new Checkbox("C++", cbg, false); {
checkBox1.setBounds(100,100, 50,50); CheckboxGroupExample(){
Checkbox checkBox2 = new Checkbox("Java", cbg, true); Frame f= new Frame("CheckboxGroup Example");
checkBox2.setBounds(100,150, 50,50); final Label label = new Label();
f.add(checkBox1); label.setAlignment(Label.CENTER);
f.add(checkBox2); label.setSize(400,100);
f.setSize(400,400); CheckboxGroup cbg = new CheckboxGroup();
f.setLayout(null); Checkbox checkBox1 = new Checkbox("C++", cbg, false);
f.setVisible(true); checkBox1.setBounds(100,100, 50,50);
} Checkbox checkBox2 = new Checkbox("Java", cbg, false);
public static void main(String args[]) checkBox2.setBounds(100,150, 50,50);
{ f.add(checkBox1); f.add(checkBox2); f.add(label);
new CheckboxGroupExample(); f.setSize(400,400);
} f.setLayout(null);
} f.setVisible(true);
Output: checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Java AWT CheckboxGroup Example with Output:
ItemListener
import java.awt.*;
import java.awt.event.*;
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 22
java.awt.Component
java.lang.Object
The object of Choice class is used to show popup menu of choices. Choice 2. void It adds the item listener that
selected by user is shown on the top of a menu. It inherits Component class. addItemListener(ItemListener l) receives item events from the
choice menu.
AWT Choice Class Declaration 3. void addNotify() It creates the peer of choice.
public class Choice extends Component implements ItemSelectable, Acces 4. AccessibleContext It gets the accessbile context
sible getAccessibleContext() related to the choice.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 23
9. int getSelectedIndex() Returns the index of the 19. void removeItemListener It removes the mentioned item
currently selected item. (ItemListener l) listener. Thus is doesn't receive
item events from the choice
10. String getSelectedItem() Gets a representation of the menu anymore.
current choice as a string.
20. void select(int pos) It changes / sets the selected
11. Object[] getSelectedObjects() Returns an array (length 1) item in the choice menu to the
containing the currently item at given index position.
selected item.
21. void select(String str) It changes / sets the selected
12. void insert(String item, int Inserts the item into this choice item in the choice menu to the
index) at the specified position. item whose string value is equal
to string specified in the
13. protected String paramString() Returns a string representing argument.
the state of this Choice menu.
14. protected void It processes the event on the Java AWT Choice Example
processEvent(AWTEvent e) choice.
In the following example, we are creating a choice menu using Choice()
15. protected void Processes item events
constructor. Then we add 5 items to the menu using add() method and Then
processItemEvent (ItemEvent occurring on this Choice menu
add the choice menu into the Frame.
e) by dispatching them to any
registered ItemListener objects.
ChoiceExample1.java
// importing awt class
16. void remove(int position) It removes an item from the
import java.awt.*;
choice menu at the given index
public class ChoiceExample1 {
position.
17. void remove(String item) It removes the first occurrence // class constructor
of the item from choice menu. ChoiceExample1() {
18. void removeAll() It removes all the items from // creating a frame
the choice menu. Frame f = new Frame();
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 24
Choice c = new Choice();
// class constructor
ChoiceExample2() {
// creating a frame
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 25
Frame f = new Frame(); f.setSize(400, 400);
f.setLayout(null);
// creating a final object of Label class f.setVisible(true);
final Label label = new Label();
// adding event to the button
// setting alignment and size of label component // which displays the selected item from the list when button is clicked
label.setAlignment(Label.CENTER);
label.setSize(400, 100); b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// creating a button String data = "Programming language Selected: "+ c.getItem(c.getSele
Button b = new Button("Show"); ctedIndex());
label.setText(data);
// setting the bounds of button }
b.setBounds(200, 100, 50, 20); });
}
// creating final object of Choice class
final Choice c = new Choice(); // main method
public static void main(String args[])
// setting bounds of choice menu {
c.setBounds(100, 100, 75, 75); new ChoiceExample2();
}
// adding 5 items to choice menu }
c.add("C"); Output:
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 26
Java AWT List java.lang.Object
The object of List class represents a list of text items. With the help of the List Class Methods
List class, user can choose either one item or multiple items. It inherits the
Component class.
Sr. Method name Description
no
AWT List class Declaration .
public class List extends Component implements ItemSelectable, Accessibl
1. void add(String item) It adds the specified item into the
e
end of scrolling list.
AWT List Class Constructors 2. void add(String item, int It adds the specified item into list
index) at the given index position.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 27
9. String getItem(int index) It fetches the item related to given 21. String[] It gets the selected items on the
index position. getSelectedItems() list.
10. int getItemCount() It gets the count/number of items 22. Object[] It gets the selected items on
in the list. getSelectedObjects() scrolling list in array of objects.
11. ItemListener[] It returns an array of item listeners 23. int getVisibleIndex() It gets the index of an item which
getItemListeners() registered on the list. was made visible by method
makeVisible()
12. String[] getItems() It fetched the items from the list.
24. void makeVisible(int It makes the item at given index
13. Dimension It gets the minimum size of a index) visible.
getMinimumSize() scrolling list.
25. boolean It returns true if given item in the
14. Dimension It gets the minimum size of a list isIndexSelected(int list is selected.
getMinimumSize(int with given number of rows. index)
rows)
26. boolean It returns the true if list allows
15. Dimension It gets the preferred size of list. isMultipleMode() multiple selections.
getPreferredSize()
27. protected String It returns parameter string
16. Dimension It gets the preferred size of list with paramString() representing state of the scrolling
getPreferredSize(int given number of rows. list.
rows)
28. protected void It process the action events
17. int getRows() It fetches the count of visible rows processActionEvent(Acti occurring on list by dispatching
in the list. onEvent e) them to a registered
ActionListener object.
18. int getSelectedIndex() It fetches the index of selected
item of list. 29. protected void It process the events on scrolling
processEvent(AWTEvent list.
19. int[] It gets the selected indices of the e)
getSelectedIndexes() list.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 28
30. protected void It process the item events Java AWT List Example
processItemEvent(ItemE occurring on list by dispatching
vent e) them to a registered ItemListener In the following example, we are creating a List component with 5 rows and
object. adding it into the Frame.
35. void removeAll() It removes all the items from the // setting the position of list component
list. l1.setBounds(100, 100, 75, 75);
36. void replaceItem(String It replaces the item at the given // adding list items into the list
newVal, int index) index in list with the new string l1.add("Item 1");
specified. l1.add("Item 2");
l1.add("Item 3");
37. void select(int index) It selects the item at given index in l1.add("Item 4");
the list. l1.add("Item 5");
38. void It sets the flag which determines // adding the list to frame
setMultipleMode(boole whether the list will allow multiple f.add(l1);
an b) selection or not.
// setting size, layout and visibility of frame
39. void removeNotify() It removes the peer of list. f.setSize(400, 400);
f.setLayout(null);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 29
f.setVisible(true); public class ListExample2
} {
// class constructor
// main method ListExample2() {
public static void main(String args[]) // creating the frame
{ Frame f = new Frame();
new ListExample1(); // creating the label which is final
} final Label label = new Label();
}
Output: // setting alignment and size of label
label.setAlignment(Label.CENTER);
label.setSize(500, 100);
// creating a button
Button b = new Button("Show");
ListExample2.java
final List l2=new List(4, true);
// importing awt and event class
l2.setBounds(100, 200, 70, 70);
import java.awt.*;
l2.add("Turbo C++");
import java.awt.event.*;
l2.add("Spring");
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 30
l2.add("Hibernate"); Output:
l2.add("CodeIgniter");
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 31
JSlider(int creates a slider using the given orientation, min, panel.add(slider);
orientation, int max and value. add(panel);
min, int max, int }
value)
public void is used to set the major tick spacing to the Output:
setMajorTickSpacing(int n) slider.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 32
JPanel panel=new JPanel(); JSpinner() It is used to construct a spinner with an Integer
panel.add(slider); SpinnerNumberModel with initial value 0 and
add(panel); no minimum or maximum limits.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 33
1); //step public class Canvas extends Component implements Accessible
JSpinner spinner = new JSpinner(value);
spinner.setBounds(100,100,50,30);
Canvas Class Constructors
f.add(spinner);
f.setSize(300,300); Sr. Constructor Description
f.setLayout(null); no.
f.setVisible(true);
1. Canvas() It constructs a new Canvas.
}
} 2. Canvas(GraphicConfiguration It constructs a new Canvas with
config) the given Graphic Configuration
Output: object.
Class methods
Java AWT Canvas Example // class which inherits the Canvas class
// to create Canvas
class MyCanvas extends Canvas
In the following example, we are creating a Canvas in the Frame and painting
{
a red colored oval inside it.
// class constructor
CanvasExample.java public MyCanvas() {
// importing awt class setBackground (Color.GRAY);
import java.awt.*; setSize(300, 200);
}
// class to construct a frame and containing main method
public class CanvasExample // paint() method to draw inside the canvas
{ public void paint(Graphics g)
// class constructor {
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 35
// adding specifications
g.setColor(Color.red);
Scrollbar Class Fields
g.fillOval(75, 75, 150, 75);
The fields of java.awt.Image class are as follows:
}
}
static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
Output:
static int VERTICAL - It is a constant to indicate a vertical scroll bar.
It can be added to top-level container like Frame or a component like Panel. Orientation: specified whether the scrollbar will be horizontal or vertical.
The Scrollbar class extends the Component class.
Value: specify the starting position of the knob of Scrollbar on its track.
AWT Scrollbar Class Declaration Minimum: specify the minimum width of track on which scrollbar is moving.
public class Scrollbar extends Component implements Adjustable, Accessi Maximum: specify the maximum width of track on which scrollbar is
ble moving.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 36
Method Inherited by Scrollbar 7. int getUnitIncrement() It fetches the unit increment of
the scroll bar.
The methods of Scrollbar class are inherited from the following classes:
8. int getValue() It fetches the current value of
java.awt.Component scroll bar.
Scrollbar Class Methods 10. boolean getValueIsAdjusting() It returns true if the value is in
process of changing where
action results are being taken
Sr. Method name Description by the user.
no.
11. protected String paramString() It returns a string representing
1. void addAdjustmentListener It adds the given adjustment the state of Scroll bar.
(AdjustmentListener l) listener to receive instances of
AdjustmentEvent from the 12. protected void It processes the adjustment
scroll bar. processAdjustmentEvent event occurring on scroll bar by
(AdjustmentEvent e) dispatching them to any
2. void addNotify() It creates the peer of scroll bar. registered AdjustmentListener
objects.
3. int getBlockIncrement() It gets the block increment of
the scroll bar. 13. protected void It processes the events on the
processEvent(AWTEvent e) scroll bar.
4. int getMaximum() It gets the maximum value of
the scroll bar. 14. void It removes the given
removeAdjustmentListener adjustment listener. Thus it no
5. int getMinimum() It gets the minimum value of (AdjustmentListener l) longer receives the instances of
the scroll bar. AdjustmentEvent from the
scroll bar.
6. int getOrientation() It returns the orientation of
scroll bar. 15. void setBlockIncrement(int v) It sets the block increment
from scroll bar.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 37
16. void setMaximum (int It sets the maximum value of FooListeners on the scroll bar
newMaximum) the scroll bar. currently.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 38
// main method
public static void main(String args[]) { public class ScrollbarExample2 {
new ScrollbarExample1();
} // class constructor
} ScrollbarExample2() {
Output: // creating a Frame with a title
Frame f = new Frame("Scrollbar Example");
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 39
label.setText("Vertical Scrollbar value is:"+ s.getValue()); public class MenuItem extends MenuComponent implements Accessible
}
});
}
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessi
// main method
ble
public static void main(String args[]){
new ScrollbarExample2();
} Java AWT MenuItem and Menu Example
}
Output: import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
Java AWT MenuItem and Menu menu.add(i2);
menu.add(i3);
The object of MenuItem class adds a simple labeled menu item on menu. submenu.add(i4);
The items used in a menu must belong to the MenuItem or any of its submenu.add(i5);
subclass. menu.add(submenu);
mb.add(menu);
The object of Menu class is a pull down menu component which is displayed f.setMenuBar(mb);
on the menu bar. It inherits the MenuItem class. f.setSize(400,400);
f.setLayout(null);
AWT MenuItem class declaration f.setVisible(true);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 40
} {
public static void main(String args[]) PopupMenuExample(){
{ final Frame f= new Frame("PopupMenu Example");
new MenuExample(); final PopupMenu popupmenu = new PopupMenu("Edit");
} MenuItem cut = new MenuItem("Cut");
} cut.setActionCommand("Cut");
Output: MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
Java AWT PopupMenu f.setSize(400,400);
f.setLayout(null);
PopupMenu can be dynamically popped up at specific position within a f.setVisible(true);
component. It inherits the Menu class. }
public static void main(String args[])
{
AWT PopupMenu class declaration new PopupMenuExample();
}
public class PopupMenu extends Menu implements MenuContainer, Acce }
ssible Output:
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 41
Java AWT Panel Example
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
Java AWT Panel new PanelExample();
}
The Panel is a simplest container class. It provides space in which an }
application can attach any other component. It inherits the Container class. Output:
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 42
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
Java AWT Dialog new DialogExample();
}
The Dialog control represents a top level window with a border and a title
}
used to take some form of input from the user. It inherits the Window class.
Output:
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttons but Dialog doesn't have.
AWT Dialog class declaration
public class Dialog extends Window
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 43
Applet Life Cycle in Java the initialized objects, i.e., the web browser (after checking the security settings)
runs the init() method within the applet.
In Java, an applet is a special type of program embedded in the web page to o start(): The start() method contains the actual code of the applet and starts
generate dynamic content. Applet is a class in Java.
the applet. It is invoked immediately after the init() method is invoked. Every time
The applet life cycle can be defined as the process of how the object is the browser is loaded or refreshed, the start() method is invoked. It is also invoked
created, started, stopped, and destroyed during the entire execution of its whenever the applet is maximized, restored, or moving from one tab to another in
application. It basically has five core methods namely init(), start(), stop(),
the browser. It is in an inactive state until the init() method is invoked.
paint() and destroy().These methods are invoked by the browser to execute.
o stop(): The stop() method stops the execution of the applet. The stop ()
Along with the browser, the applet also works on the client side, thus having method is invoked whenever the applet is stopped, minimized, or moving from one
less processing time.
tab to another in the browser, the stop() method is invoked. When we go back to
that page, the start() method is invoked again.
Methods of Applet Life Cycle
o destroy(): The destroy() method destroys the applet after its work is done.
It is invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is executed only
once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used
to draw shapes like circle, square, trapezium, etc., in the applet. It is executed after
the start() method and when the browser or applet windows are resized.
1. init()
2. start()
There are five methods of an applet life cycle, and they are: 3. paint()
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 44
1. stop()
2. destroy()
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 45
// code to destroy the applet 3) AWT doesn't support pluggable look Swing supports
} and feel. pluggable look and feel.
}
4) AWT provides less components than Swing provides more
Swing. powerful
components such as
Java Swing tables, lists, scrollpanes,
colorchooser,
Java Swing is a part of Java Foundation Classes (JFC) that is used to create tabbedpane etc.
window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java. 5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
Unlike AWT, Java Swing provides platform-independent and lightweight represents data, view represents
components. presentation and controller acts as
an interface between model and
The javax.swing package provides classes for java swing API such as JButton, view.
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
Difference between AWT and Swing The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
There are many differences between java awt and swing that are given
Do You Know
below.
o How to create runnable jar file in java?
No. Java AWT Java Swing o How to display image on a button in swing?
o How to change the component color by choosing a color from
1) AWT components are platform- Java swing components
ColorChooser ?
dependent. are platform-
independent. o How to display the digital watch in swing tutorial ?
2) AWT components are heavyweight. Swing components o How to create a notepad in swing?
are lightweight. o How to create puzzle game and pic puzzle game in swing ?
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 46
o How to create tic tac toe game in swing ?
Method Description
Hierarchy of Java Swing classes public void add(Component c) add a component on another
The hierarchy of java swing API is given below. public void setSize(int width,int height) sets size of the component.
We can write the code of swing inside the main(), constructor or any other
method.
The methods of Component class are widely used in java swing that are 1. import javax.swing.*;
given below. 2. public class FirstSwingExample {
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 47
3. public static void main(String[] args) { Example of Swing by Association inside
4. JFrame f=new JFrame();//creating instance of JFrame
constructor
5.
6. JButton b=new JButton("click");//creating instance of JButton We can also write all the codes of creating JFrame, JButton and method call
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height inside the java constructor.
8. File: Simple.java
9. f.add(b);//adding button in JFrame
10. import javax.swing.*;
11. f.setSize(400,500);//400 width and 500 height public class Simple {
12. f.setLayout(null);//using no layout managers JFrame f;
13. f.setVisible(true);//making the frame visible Simple(){
14. } f=new JFrame();//creating instance of JFrame
15. }
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 48
Java LayoutManagers 4. public static final int WEST
5. public static final int CENTER
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 Constructors of BorderLayout class:
is implemented by all the classes of layout managers. There are the following
classes that represent the layout managers: o BorderLayout(): creates a border layout but with no gaps between the
components.
1. java.awt.BorderLayout
o BorderLayout(int hgap, int vgap): creates a border layout with the given
2. java.awt.FlowLayout horizontal and vertical gaps between the components.
3. java.awt.GridLayout
4. java.awt.CardLayout
Example of BorderLayout class: Using BorderLayout()
constructor
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout FileName: Border.java
7. javax.swing.GroupLayout
import java.awt.*;
8. javax.swing.ScrollPaneLayout
import javax.swing.*;
9. javax.swing.SpringLayout etc.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 49
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST Java GridLayout
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 50
JFrame frameObj; frameObj.setLayout(new GridLayout());
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 51
Fields of FlowLayout class {
1. FlowLayout(): creates a flow layout with centered alignment and a // creating the buttons
default 5 unit horizontal and vertical gap. JButton b1 = new JButton("1");
2. FlowLayout(int align): creates a flow layout with the given alignment JButton b2 = new JButton("2");
and a default 5 unit horizontal and vertical gap. JButton b3 = new JButton("3");
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with JButton b4 = new JButton("4");
the given alignment and the given horizontal and vertical gap. JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
Example of FlowLayout class: Using FlowLayout() JButton b7 = new JButton("7");
constructor JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
FileName: FlowLayoutExample.java
JButton b10 = new JButton("10");
// import statements
import java.awt.*;
// adding the buttons to frame
import javax.swing.*;
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 52
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8)
;
frameObj.add(b9); frameObj.add(b10);
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 53
The core advantage of exception handling is to maintain the normal flow of
Exception Handling in Java the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a
1. Exception Handling scenario:
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 54
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
Types of Java Exceptions
The classes that directly inherit the Throwable class except
There are mainly two types of exceptions: checked and unchecked. An error RuntimeException and Error are known as checked exceptions. For example,
is considered as the unchecked exception. However, according to Oracle, IOException, SQLException, etc. Checked exceptions are checked at
there are three types of exceptions namely: compile-time.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 55
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
It doesn't throw an exception. It is always used with method
checked at compile-time, but they are checked at runtime.
signature.
3) Error
Java Exception Handling Example
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
Java Exception Keywords
JavaExceptionExample.java
Java provides five keywords that are used to handle the exception. The
following table describes each. public class JavaExceptionExample{
public static void main(String args[]){
Keyword Description try{
//code that may raise exception
try The "try" keyword is used to specify a block where we
int data=100/0;
should place an exception code. It means we can't use try
block alone. The try block must be followed by either catch }catch(ArithmeticException e)
or finally. {
System.out.println(e);
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. //rest code of the program
System.out.println("rest of the code...");
finally The "finally" block is used to execute the necessary code of
the program. It is executed whether an exception is handled }
or not. }
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 56
A scenario where ArithmeticException occurs
Java try-catch block
If we divide any number by zero, there occurs an ArithmeticException.
Java try block
int a=50/0;//ArithmeticException
Java try block is used to enclose the code that might throw an exception. It
2) A scenario where NullPointerException occurs must be used within the method.
If we have a null value in any variable, performing any operation on the If an exception occurs at the particular statement in the try block, the rest
variable throws a NullPointerException. 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.
String s=null;
Java try block must be followed by either catch or finally block.
System.out.println(s.length());//NullPointerException
If the formatting of any variable or number is mismatched, it may result into try{
NumberFormatException. Suppose we have a string variable that has //code that may throw an exception
characters; converting this variable into digit will cause
}catch(Exception_class_Name ref){}
NumberFormatException.
String s="abc";
Syntax of try-finally block
int i=Integer.parseInt(s);//NumberFormatException
try{
4) A scenario where ArrayIndexOutOfBoundsException occurs //code that may throw an exception
}finally{}
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
Java catch block
Java catch block is used to handle the Exception by declaring the type of
int a[]=new int[5]; exception within the parameter. The declared exception must be the parent
a[10]=50; //ArrayIndexOutOfBoundsException class exception ( i.e., Exception) or the generated exception type. However,
the good approach is to declare the generated type of exception.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 57
The catch block must be used after the try block only. You can use multiple TryCatchExample2.java
catch block with a single try block.
public class TryCatchExample2 {
Internal Working of Java try-catch block
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
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 Java Catch Multiple Exceptions
following tasks:
But if the application programmer handles the exception, the normal flow
of the application is maintained, i.e., rest of the code is executed. Points to remember
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 58
o At a time only one exception occurs and at a time only one catch
block is executed. try{
o All catch blocks must be ordered from most specific to most general, int a[]=new int[5];
i.e. catch for ArithmeticException must come before catch for Exception. a[5]=30/0;
}
Flowchart of Multi-catch Block catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
Example 1 }
}
Let's see a simple example of java multi-catch block.
Java finally block
MultipleCatchBlock1.java
Java finally block is a block used to execute important code such as closing
public class MultipleCatchBlock1 { the connection, etc.
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 59
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
Usage of Java finally
regardless of the exception occurs or not.
Let's see the different cases where Java finally block can be used.
The finally block follows the try-catch block.
Case 1: When an exception does not occur
Flowchart of finally block
Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any). }
//executed regardless of exception occurred or not
UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 60