0% found this document useful (0 votes)
9 views60 pages

UNIT 3 Event and GUI Programming in Java

Uploaded by

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

UNIT 3 Event and GUI Programming in Java

Uploaded by

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

The java.

awt package provides classes for AWT API such


UNIT 3
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Event and GUI programming in java


Why AWT is platform independent?
Event and GUI programming: Event handling in java,
Java AWT calls the native platform calls the native platform (operating
Event types, Mouse and key events, GUI Basics, Panels,
systems) subroutine for creating API components like TextField, ChechBox,
Frames, Layout Managers: Flow Layout, Border Layout, button, etc.

Grid Layout, GUI components like Buttons, Check Boxes,


For example, an AWT GUI with components like TextField, label and button
Radio Buttons, Labels, Text Fields, Text Areas, Combo will have different look and feel for the different platforms like Windows,

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.

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).

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.

Note: A container itself is a component (see the above diagram), therefore we


can add a container inside container.

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
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.*;

// extending Frame class to our class AWTExample1


Useful Methods of Component Class public class AWTExample1 extends Frame {

// initializing using constructor


Method Description AWTExample1() {

public void add(Component c) Inserts a component on this component. // creating a button


Button b = new Button("Click Me!!");
public void setSize(int width,int Sets the size (width and height) of the
height) component. // setting button position on screen
b.setBounds(30,100,80,30);
public void Defines the layout manager for the
setLayout(LayoutManager m) component. // adding button into frame
add(b);
public void setVisible(boolean Changes the visibility of the component, by
status) default false. // frame size 300 width and 300 height
setSize(300,300);

Java AWT Example // setting the title of Frame


setTitle("This is our basic AWT example");
To create simple AWT example, you need a frame. There are two ways to
create a GUI using Frame in AWT. // no layout manager
setLayout(null);
By extending Frame class (inheritance)
// now frame will be visible, by default it is not visible
setVisible(true);
By creating the object of Frame class (association)
}

AWT Example by Inheritance // main method


public static void main(String args[]) {

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:");

Output: // creating a Button


Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
AWT Example by Association f.add(t);

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");

// importing Java AWT class // no layout


import java.awt.*; f.setLayout(null);

// 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

// creating instance of Frame class ItemEvent ItemListener


AWTExample2 awt_obj = new AWTExample2();
TextEvent TextListener
}
} AdjustmentEvent AdjustmentListener
Output:
WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Event and Listener (Java Event Handling)
Following steps are required to perform event handling:
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes Register
and the component with the Listener
Listener interfaces for event handling.
Registration Methods
Java Event classes and Listener interfaces
For registering the component with the Listener, many classes provide the
registration methods. For example:
Event Classes Listener Interfaces
Button
ActionEvent ActionListener
public void addActionListener(ActionListener a){}
MouseEvent MouseListener and MouseMotionListener
MenuItem

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 5
public void addActionListener(ActionListener a){} Anonymous class

TextField Java event handling by implementing ActionListener


public void addActionListener(ActionListener a){} import java.awt.*;
import java.awt.event.*;
public void addTextListener(TextListener a){} class AEvent extends Frame implements ActionListener{
TextField tf;
TextArea
AEvent(){
public void addTextListener(TextListener a){}
//create components
tf=new TextField();
Checkbox
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
public void addItemListener(ItemListener a){}
b.setBounds(100,120,80,30);
Choice
//register listener
public void addItemListener(ItemListener a){} b.addActionListener(this);//passing current instance

List //add components and set size, layout and visibility


add(b);add(tf);
public void addActionListener(ActionListener a){} setSize(300,300);
setLayout(null);
public void addItemListener(ItemListener a){} setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
Java Event Handling Code public static void main(String args[]){
new AEvent();
We can put the event handling code into one of the following places: }
}
Within 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()

7. void It adds the specified action listener to get the


Button Class Constructors addActionListener( action events from the button.
ActionListener l)
Following table shows the types of Button class constructors

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

9. ActionListener[ ] It returns an array of all the action listeners import java.awt.*;


getActionListeners registered on the button. public class ButtonExample {
() public static void main (String[] args) {

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

If there's no error, we can execute the code using:


Note: The Button class inherits methods from java.awt.Component and
java.lang.Object classes. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample

Java AWT Button Example Output:

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.*;

public class ButtonExample2


{ Java AWT Button Example with ActionListener
// creating instances of Frame class and Button class
Frame fObj;
Button button1, button2, button3; Example:
// instantiating using the constructor
ButtonExample2() { In the following example, we are handling the button click events by
fObj = new Frame ("Frame to display buttons"); implementing ActionListener Interface.
button1 = new Button();
button2 = new Button ("Click here"); ButtonExample3.java
button3 = new Button();
button3.setLabel("Button 3"); // importing necessary libraries
fObj.add(button1); import java.awt.*;
fObj.add(button2); import java.awt.event.*;
fObj.add(button3); public class ButtonExample3 {
fObj.setLayout(new FlowLayout()); public static void main(String[] args) {
fObj.setSize(300,400); // create instance of frame with the label
fObj.setVisible(true); Frame f = new Frame("Button Example");
} final TextField tf=new TextField();
// main method tf.setBounds(50,50, 150,20);

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.

3. TextField(int It constructs a new textfield (empty) with


columns) given number of columns.

4. TextField(String It constructs a new text field with the given


text, int text and given number of columns (width).
columns)

Java AWT TextField TextField Class Methods


The object of a TextField class is a text component that allows a user to
enter a single line text and edit it. It inherits TextComponent class, which
further inherits Component class.

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

Java AWT TextField Example


TextFieldExample1.java
// importing AWT class
import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) { Java AWT TextField Example with
// creating a frame
Frame f = new Frame("TextField Example");
ActionListener
TextFieldExample2.java
// creating objects of textfield
// importing necessary libraries
TextField t1, t2;
import java.awt.*;
// instantiating the textfield objects
import java.awt.event.*;
// setting the location of those objects in the frame
// Our class extends Frame class and implements ActionListener interface
t1 = new TextField("Welcome to Java.");
public class TextFieldExample2 extends Frame implements ActionListener
t1.setBounds(50, 100, 200, 30);
{
t2 = new TextField("AWT Tutorial");
// creating instances of TextField and Button class
t2.setBounds(50, 150, 200, 30);
TextField tf1, tf2, tf3;
// adding the components to frame
Button b1, b2;
f.add(t1);
// instantiating using constructor
f.add(t2);
TextFieldExample2() {
// setting size, layout and visibility of frame
// instantiating objects of text field and button
f.setSize(400,400);
// setting position of components in frame
f.setLayout(null);
tf1 = new TextField();
f.setVisible(true);
tf1.setBounds(50, 50, 150, 20);
}
tf2 = new TextField();
}
tf2.setBounds(50, 100, 150, 20);

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.

static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only


the horizontal scrollbar. Methods Inherited
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the The methods of TextArea class are inherited from following classes:
vertical scrollbar.
java.awt.TextComponent
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in
the text area. java.awt.Component

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.

6. Dimension It determines the minimum size of


getMinimumSize(int rows, a text area with the given number Java AWT TextArea Example
int columns) of rows and columns.
The below example illustrates the simple implementation of TextArea where
7. Dimension It determines the preferred size of we are creating a text area using the constructor TextArea(String text) and
getPreferredSize() a text area. adding it to the frame.

8. Dimension It determines the preferred size of TextAreaExample .java


preferredSize(int rows, int a text area with given number of
columns) rows and columns. //importing AWT class
import java.awt.*;
9. int getRows() It returns the number of rows of public class TextAreaExample
text area. {
// constructor to initialize
10. int getScrollbarVisibility() It returns an enumerated value
TextAreaExample() {
that indicates which scroll bars the
// creating a frame
text area uses.
Frame f = new Frame();
11. void insert(String str, int It inserts the specified text at the // creating a text area
pos) specified position in this text area. TextArea area = new TextArea("Welcome to java");
// setting location of text area in frame
12. protected String It returns a string representing the area.setBounds(10, 30, 300, 300);
paramString() state of this TextArea. // adding text area to frame
f.add(area);
13. void replaceRange(String It replaces text between the // setting size, layout and visibility of frame
str, int start, int end) indicated start and end positions f.setSize(400, 400);
with the specified replacement f.setLayout(null);
text. f.setVisible(true);
}

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);

// adding ActionListener to button


b.addActionListener(this);
Java AWT TextArea Example with
ActionListener // adding components to frame
add(l1);
The following example displays a text area in the frame where it extends the add(l2);
Frame class and implements ActionListener interface. Using ActionListener add(area);
the event is generated on the button press, where we are counting the add(b);
number of character and words entered in the text area. // setting the size, layout and visibility of frame
setSize(400, 450);
TextAreaExample2.java setLayout(null);
// importing necessary libraries setVisible(true);
import java.awt.*; }
import java.awt.event.*; // generating event text area to count number of words and characters
// our class extends the Frame class to inherit its properties public void actionPerformed(ActionEvent e) {
// and implements ActionListener interface to override its methods String text = area.getText();

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.

3. Checkbox(String label, It constructs a checkbox with the given


boolean state) label and sets the given state.

4. Checkbox(String label, It constructs a checkbox with the given


boolean state, label, set the given state in the specified
CheckboxGroup group) checkbox group.

5. Checkbox(String label, It constructs a checkbox with the given


CheckboxGroup group, label, in the given checkbox group and
boolean state) set to the specified state.
Java AWT Checkbox
Method inherited by Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option
on (true) or off (false). Clicking on a Checkbox changes its state from "on" to The methods of Checkbox class are inherited by following classes:
"off" or from "off" to "on".
java.awt.Component
AWT Checkbox Class Declaration
java.lang.Object
public class Checkbox extends Component implements ItemSelectable, Ac
cessible Checkbox Class Methods

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);

// adding event to the checkboxes


checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
} Java AWT CheckboxGroup
});
checkbox2.addItemListener(new ItemListener() { The object of CheckboxGroup class is used to group together a set
public void itemStateChanged(ItemEvent e) { of Checkbox. At a time only one check box button is allowed to be in "on"
label.setText("Java Checkbox: " state and remaining check box button in "off" state. It inherits the object
+ (e.getStateChange()==1?"checked":"unchecked")); class.
}
}); Note: CheckboxGroup enables you to create radio buttons in AWT. There is no
// setting size, layout and visibility of frame special control for creating radio buttons in AWT.
f.setSize(400,400);
f.setLayout(null); AWT CheckboxGroup Class Declaration
f.setVisible(true);
}
public class CheckboxGroup extends Object implements Serializable
// main method
public static void main(String args[])
{ Java AWT CheckboxGroup Example
new CheckboxExample2();
} import java.awt.*;
} public class CheckboxGroupExample
Output: {
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");

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

Choice Class Methods

Sr. Method name Description


no.

1. void add(String item) It adds an item to the choice


Java AWT Choice menu.

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.

5. String getItem(int index) It gets the item (string) at the


Choice Class constructor given index position in the
choice menu.
Sr. no. Constructor Description
6. int getItemCount() It returns the number of items
of the choice menu.
1. Choice() It constructs a new choice menu.
7. ItemListener[] It returns an array of all item
getItemListeners() listeners registered on choice.
Methods inherited by class
8. T[] Returns an array of all the
The methods of Choice class are inherited by following classes: getListeners(Class listenerType) objects currently registered as
FooListeners upon this 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();

// creating a choice component

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 24
Choice c = new Choice();

// setting the bounds of choice menu


c.setBounds(100, 100, 75, 75);

// adding items to the choice menu


c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");

// adding choice menu to frame


f.add(c);

// setting size, layout and visibility of frame


f.setSize(400, 400);
Java AWT Choice Example with ActionListener
f.setLayout(null);
f.setVisible(true); In the following example, we are creating a choice menu with 5 items. Along
} with that we are creating a button and a label. Here, we are adding an event
to the button component using addActionListener(ActionListener a)
// main method method i.e. the selected item from the choice menu is displayed on the label
public static void main(String args[]) when the button is clicked.
{
new ChoiceExample1(); ChoiceExample2.java
} // importing necessary packages
} import java.awt.*;
Output: import java.awt.event.*;

public class ChoiceExample2 {

// 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");

// adding above components into the frame


f.add(c);
f.add(label);
f.add(b);

// setting size, layout and visibility of frame

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.

Sr. Constructor Description 3. void It adds the specified action listener


no. addActionListener(Actio to receive action events from list.
nListener l)
1. List() It constructs a new scrolling list.
4. void It adds specified item listener to
2. List(int row_num) It constructs a new scrolling list addItemListener(ItemLis receive item events from list.
initialized with the given number of tener l)
rows visible.
5. void addNotify() It creates peer of list.
3. List(int row_num, It constructs a new scrolling list
Boolean initialized which displays the given 6. void deselect(int index) It deselects the item at given index
multipleMode) number of rows. position.

7. AccessibleContext It fetches the accessible context


Methods Inherited by the List Class getAccessibleContext() related to the list.

8. ActionListener[] It returns an array of action


The List class methods are inherited by following classes:
getActionListeners() listeners registered on the list.
java.awt.Component

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.

20. String getSelectedItem() It gets the selected item on the 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.

31. void It removes specified action ListExample1.java


removeActionListener(A listener. Thus it doesn't receive // importing awt class
ctionListener l) further action events from the list. import java.awt.*;

32. void It removes specified item listener. public class ListExample1


removeItemListener(Ite Thus it doesn't receive further {
mListener l) action events from the list. // class constructor
ListExample1() {
33. void remove(int It removes the item at given index
// creating the frame
position) position from the list.
Frame f = new Frame();
// creating the list of 5 rows
34. void remove(String It removes the first occurrence of
List l1 = new List(5);
item) an item from list.

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");

// setting location of button


b.setBounds(200, 150, 80, 30);

// creating the 2 list objects of 4 rows


// adding items to the list using add()
// setting location of list components
Java AWT List Example with ActionListener final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
In the following example, we are creating two List components, a Button and
l1.add("C");
a Label and adding them into the frame. Here, we are generating an event
l1.add("C++");
on the button using the addActionListener(ActionListener l) method. On
l1.add("Java");
clicking the button, it displays the selected programming language and the
l1.add("PHP");
framework.

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");

// adding List, Label and Button to the frame


f.add(l1);
f.add(l2);
f.add(label);
f.add(b);

// setting size, layout and visibility of frame


f.setSize(450,450);
f.setLayout(null);
f.setVisible(true); Java JSlider
// generating event on the button The Java JSlider class is used to create the slider. By using JSlider, a user can
b.addActionListener(new ActionListener() { select a value from a specific range.
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+l1.getItem(l1.getSel
ectedIndex());
Commonly used Constructors of JSlider class
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()) { Constructor Description
data += frame + " ";
}
JSlider() creates a slider with the initial value of 50 and
label.setText(data);
range of 0 to 100.
}
}); JSlider(int creates a slider with the specified orientation set by
} orientation) either JSlider.HORIZONTAL or JSlider.VERTICAL
with the range 0 to 100 and initial value 50.
// main method
public static void main(String args[]) JSlider(int min, int creates a horizontal slider using the given min and
{ max) max.
new ListExample2();
} JSlider(int min, int creates a horizontal slider using the given min, max
} max, int value) and value.

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 static void main(String s[]) {


Commonly used Methods of JSlider class SliderExample1 frame=new SliderExample1();
frame.pack();
Method Description frame.setVisible(true);
}
public void is used to set the minor tick spacing to
setMinorTickSpacing(int n) the slider. }

public void is used to set the major tick spacing to the Output:
setMajorTickSpacing(int n) slider.

public void is used to determine whether tick marks


setPaintTicks(boolean b) are painted.

public void is used to determine whether labels are


setPaintLabels(boolean b) painted.
Java JSlider Example: painting ticks
public void is used to determine whether track is
setPaintTracks(boolean b) painted. import javax.swing.*;
public class SliderExample extends JFrame{
Java JSlider Example public SliderExample() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
import javax.swing.*; slider.setMinorTickSpacing(2);
public class SliderExample1 extends JFrame{ slider.setMajorTickSpacing(10);
public SliderExample1() { slider.setPaintTicks(true);
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); slider.setPaintLabels(true);
JPanel panel=new JPanel();

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.

} JSpinner(SpinnerModel It is used to construct a spinner for a given


public static void main(String s[]) { model) model.
SliderExample frame=new SliderExample();
frame.pack();
frame.setVisible(true); Commonly used Methods:
}
} Method Description

Java JSpinner void It is used to add a listener to the list


addChangeListener(ChangeListener that is notified each time a change
The object of JSpinner class is a single line input field that allows the user to listener) to the model occurs.
select a number or an object value from an ordered sequence.
Object getValue() It is used to return the current
value of the model.

JSpinner class declaration


Java JSpinner Example
Let's see the declaration for javax.swing.JSpinner class.
import javax.swing.*;
1. public class JSpinner extends JComponent implements Accessible
public class SpinnerExample {

Commonly used Contructors: public static void main(String[] args) {


JFrame f=new JFrame("Spinner Example");
SpinnerModel value =
Constructor Description
new SpinnerNumberModel(5, //initial value
0, //minimum value
10, //maximum value

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

Sr. Method name Description


no.

1. void addNotify() It creates the canvas's peer.

2. void It creates a new multi buffering


createBufferStrategy strategies on the particular
(int numBuffers) component.

Java AWT Canvas 3. void It creates a new multi buffering


createBufferStrategy strategies on the particular component
The Canvas class controls and represents a blank rectangular area where the (int numBuffers, with the given buffer capabilities.
application can draw or trap input events from the user. It inherits BufferCapabilities
the Component class. caps)

AWT Canvas class Declaration


UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 34
public CanvasExample()
4. AccessibleContext It gets the accessible context related to
{
getAccessibleContext() the Canvas.

5. BufferStrategy It returns the buffer strategy used by // creating a frame


getBufferStrategy() the particular component. Frame f = new Frame("Canvas Example");
// adding canvas to frame
6. void paint(Graphics g) It paints the canvas with given Graphics f.add(new MyCanvas());
object.
// setting layout, size and visibility of frame
7. void pdate(Graphics g) It updates the canvas with given f.setLayout(null);
Graphics object. f.setSize(400, 400);
f.setVisible(true);
}
Method Inherited by Canvas Class
// main method
The Canvas has inherited above methods from the following classes: public static void main(String args[])
{
lang.Component new CanvasExample();
}
lang.Object }

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.

Scrollbar Class Constructors

Sr. Constructor Description


no.

1 Scrollbar() Constructs a new vertical scroll bar.

2 Scrollbar(int orientation) Constructs a new scroll bar with the


specified orientation.

3 Scrollbar(int orientation, Constructs a new scroll bar with the


int value, int visible, int specified orientation, initial value,
Java AWT Scrollbar minimum, int maximum) visible amount, and minimum and
maximum values.
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns. Where the parameters,

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.

java.lang.Object 9. int getVisibleAmount() It fetches the visible amount of


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.

17. void setMinimum (int It sets the minimum value of


newMinimum) the scroll bar. Java AWT Scrollbar Example
18. void setOrientation (int It sets the orientation for the In the following example, we are creating a scrollbar using the Scrollbar()
orientation) scroll bar. and adding it into the Frame.

19. void setUnitIncrement(int v) It sets the unit increment for ScrollbarExample1.java


the scroll bar. // importing awt package
import java.awt.*;
20. void setValue (int newValue) It sets the value of scroll bar
with the given argument value.
public class ScrollbarExample1 {
21. void setValueIsAdjusting It sets the valueIsAdjusting
// class constructor
(boolean b) property to scroll bar.
ScrollbarExample1() {
22. void setValues (int value, int It sets the values of four
visible, int minimum, int properties for scroll bar: value, // creating a frame
maximum) visible amount, minimum and Frame f = new Frame("Scrollbar Example");
maximum. // creating a scroll bar
Scrollbar s = new Scrollbar();
23. void setVisibleAmount (int It sets the visible amount of the
newAmount) scroll bar. // setting the position of scroll bar
s.setBounds (100, 100, 50, 100);
24. AccessibleContext It gets the accessible context
getAccessibleContext() related to the scroll bar. // adding scroll bar to the frame
f.add(s);
25. AdjustmentListener[] It returns an array of al lthe
getAdjustmentListeners() adjustment listeners registered // setting size, layout and visibility of frame
on the scroll bar. f.setSize(400, 400);
f.setLayout(null);
26. T[] It returns an array if all objects f.setVisible(true);
getListeners(Class listenerType) that are registered as }

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");

// creating a final object of Label


final Label label = new Label();

// setting alignment and size of label object


label.setAlignment(Label.CENTER);
label.setSize(400, 100);

// creating a final object of Scrollbar class


final Scrollbar s = new Scrollbar();

// setting the position of scroll bar


s.setBounds(100, 100, 50, 100);
Java AWT Scrollbar Example with // adding Scrollbar and Label to the Frame
AdjustmentListener f.add(s);
f.add(label);
In the following example, we are creating a Scrollbar and adding it into the
Frame. Here, we are using addAdjustmentListener() method of Scrollbar // setting the size, layout, and visibility of frame
class which receives the instances of AdjustmentEvent and eventually we f.setSize(400, 400);
display it in the form of Label. f.setLayout(null);
f.setVisible(true);
ScrollbarExample2.java
// importing necessary packages // adding AdjustmentListener to the scrollbar object
import java.awt.*; s.addAdjustmentListener(new AdjustmentListener() {
import java.awt.event.*; public void adjustmentValueChanged(AdjustmentEvent e) {

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:

Java AWT PopupMenu Example


import java.awt.*;
import java.awt.event.*;
class PopupMenuExample

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:

It doesn't have title bar.

AWT Panel class declaration


public class Panel extends Container implements Accessible

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.

Sequence of method execution when an applet is executed:

1. init()
2. start()

There are five methods of an applet life cycle, and they are: 3. paint()

Sequence of method execution when an applet is executed:


o init(): The init() method is the first method to run that initializes the applet.
It can be invoked only once at the time of initialization. The web browser creates

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 44
1. stop()
2. destroy()

Applet Life Cycle Working


o The Java plug-in software is responsible for managing the life cycle of an
applet.
o An applet is a Java application executed in any web browser and works on
the client-side. It doesn't have the main() method because it runs in the browser.
It is thus created to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to
the applet.Applet class.
Syntax of entire Applet Life Cycle in Java
o The paint() method belongs to the awt.Component class.
class TestAppletLifeCycle extends Applet {
o In Java, if we want to make a class an Applet class, we need to extend public void init() {
the Applet // initialized objects
o Whenever we create an applet, we are creating the instance of the existing }
Applet class. And thus, we can use all the methods of that class. public void start() {
// code to start the applet
Flow of Applet Life Cycle: }
public void paint(Graphics graphics) {
These methods are invoked by the browser automatically. There is no need
// draw the shapes
to call them explicitly.
}
public void stop() {
// code to stop the applet
}
public void 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.

public void setLayout(LayoutManager m) sets the layout manager for t

public void setVisible(boolean b) sets the visibility of the comp

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other
method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and
adding it on the JFrame object inside the main() method.

Commonly used Methods of Component class File: FirstSwingExample.java

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);

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}

public static void main(String[] args) {


new Simple();
}
}

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.

public class Border


Java BorderLayout
{
The BorderLayout is used to arrange the components in five regions: north, JFrame f;
south, east, west, and center. Each region (area) may contain one Border()
component only. It is the default layout of a frame or window. The
{
BorderLayout provides five constants for each region:
f = new JFrame();
1. public static final int NORTH
// creating buttons
2. public static final int SOUTH
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
3. public static final int EAST
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH

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.

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


Constructors of GridLayout class
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction 1. GridLayout(): creates a grid layout with one column per component in a
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction row.
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
f.setSize(300, 300);
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
f.setVisible(true);
layout with the given rows and columns along with given horizontal and
}
vertical gaps.
public static void main(String[] args) {
new Border();
Example of GridLayout class: Using GridLayout()
}
Constructor
}
The GridLayout() constructor creates only one row. The following example
Output: shows the usage of the parameterless constructor.

FileName: GridLayoutExample.java

// import statements
import java.awt.*;
import javax.swing.*;

public class GridLayoutExample


{

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 50
JFrame frameObj; frameObj.setLayout(new GridLayout());

// constructor frameObj.setSize(300, 300);


GridLayoutExample() frameObj.setVisible(true);
{ }
frameObj = new JFrame(); // main method
public static void main(String argvs[])
// creating 9 buttons {
JButton btn1 = new JButton("1"); new GridLayoutExample();
JButton btn2 = new JButton("2"); }
JButton btn3 = new JButton("3"); }
JButton btn4 = new JButton("4");
Output:
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");

// adding buttons to the frame


// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3); Java FlowLayout
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9); The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
// setting the grid layout using the parameterless constructor

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 51
Fields of FlowLayout class {

1. public static final int LEFT JFrame frameObj;


2. public static final int RIGHT
3. public static final int CENTER // constructor
4. public static final int LEADING FlowLayoutExample()
{
5. public static final int TRAILING
// creating a frame object
Constructors of FlowLayout class frameObj = new JFrame();

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);

public class FlowLayoutExample

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);

// parameter less constructor is used


// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());

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:

2. Advantage of Exception Handling


statement 1;
3. Hierarchy of Exception classes statement 2;
4. Types of Exception statement 3;
5. Exception Example statement 4;
6. Scenarios where an exception may occur statement 5;//exception occurs
statement 6;
The Exception Handling in Java is one of the powerful mechanism to handle statement 7;
the runtime errors so that the normal flow of the application can be
maintained. statement 8;
statement 9;
In this tutorial, we will learn about Java exceptions, it's types, and the statement 10;
difference between checked and unchecked exceptions.
Suppose there are 10 statements in a Java program and an exception occurs
What is Exception in Java? at statement 5; the rest of the code will not be executed, i.e., statements 6
to 10 will not be executed. However, when we perform exception handling,
Dictionary Meaning: Exception is an abnormal condition. the rest of the statements will be executed. That is why we use exception
handling in Java.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime. Hierarchy of Java Exception classes
What is Exception Handling? 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 Handling is a mechanism to handle runtime errors such as Exception classes is given below:
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

Advantage of Exception Handling

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.

1. Checked Exception 2) Unchecked Exception


2. Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
3. Error exceptions. For example, ArithmeticException, NullPointerException,

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. }

throw The "throw" keyword is used to throw an exception.


Common Scenarios of Java Exceptions
throws The "throws" keyword is used to declare exceptions. It
specifies that there may occur an exception in the method. There are given some scenarios where unchecked exceptions may occur.
They are as follows:

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

3) A scenario where NumberFormatException occurs Syntax of Java try-catch

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:

o Prints out exception description.


Java Multi-catch block
o Prints the stack trace (Hierarchy of methods where the exception A try block can be followed by one or more catch blocks. Each catch block
occurred). must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
o Causes the program to terminate. catch block.

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.

public static void main(String[] args) {

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

Why use Java finally block? finally {


System.out.println("finally block is always executed");
o finally block in Java can be used to put "cleanup" code such as closing a file, }
closing connection, etc. System.out.println("rest of phe code...");

o The important statements to be printed can be placed in the finally block. }


}

UNIT 3 GUI & Event programming in Java By, KAMALAKAR HEDGE Page No | 60

You might also like