Course II_BCA NEP Syllabus Krupanidhi College
Unit – 4- Event and GUI programming:
Event handling in java, Event types, Mouse and key events, GUI Basics, Panels,
Frames, Layout Managers: Flow Layout, Border Layout, Grid Layout, GUI
components like Buttons, Check Boxes, Radio Buttons, Labels, Text Fields, Text
Areas, Combo Boxes, Lists, Scroll Bars, Sliders, Windows, Menus, Dialog Box,
Applet and its life cycle, Introduction to swing, Exceptional handling mechanism.
GUI Basics
AWT stands for Abstract window toolkit is an Application programming interface
(API) for creating Graphical User Interface (GUI) in Java.
Java AWT contains large number of classes and methods to create and manage
graphical user interface ( GUI )
Containers in java
A Container is a subclass of Component that can contain other components.
There are four types of containers available in AWT:
Window,
Frame,
Dialog
Panel.
Narasimha Murthy G K Page 1
Course II_BCA NEP Syllabus Krupanidhi College
Window: An instance of the Window class has no border and no title
Dialog: Dialog class has border and title.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components.
Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing
an application in AWT.
We can create a GUI using Frame in two ways:
1) By creating the instance of Frame class
2) By extending Frame class
1) By creating the instance of Frame class
import java.awt.*;
public class AwtProgram1
{
public AwtProgram1()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
f.add(btn); //adding a new Button.
f.setSize(300, 250); //setting size.
f.setTitle("JavaTPoint"); //setting title.
f.setLayout(null); //set default layout for frame.
f.setVisible(true); //set frame visibility true.
}
public static void main(String[] args) {
AwtProgram1 awt = new AwtProgram1(); //creating a frame.
}
}
Narasimha Murthy G K Page 2
Course II_BCA NEP Syllabus Krupanidhi College
2) By extending Frame class
import java.awt.*;
public class SimpleExample extends Frame{
SimpleExample()
{
Button b=new Button("Button!!");
// setting button position on screen
b.setBounds(50,50,50,50);
//adding button into frame
add(b);
//Setting Frame width and height
setSize(500,300);
//Setting the title of Frame
setTitle("This is my First AWT example");
//Setting the layout for the Frame
setLayout(new FlowLayout());
/* By default frame is not visible so
* we are setting the visibility to true
* to make it visible.
*/
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}
Constructing a Component and Adding the Component into a Container
Three steps are necessary to create and place a GUI component:
1. Declare the component with an identifier (name);
Narasimha Murthy G K Page 3
Course II_BCA NEP Syllabus Krupanidhi College
2. Construct the component by invoking an appropriate constructor via
the new operator;
3. Identify the container (such as Frame or Panel) designed to hold this component.
The container can then add this component onto itself via a
Container.add(aComponent) method. Every container has
a add(Component) method.
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labeled button which can
perform an action.
Button Class Constructors
Example program
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
Narasimha Murthy G K Page 4
Course II_BCA NEP Syllabus Krupanidhi College
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single
line text is allowed and the text cannot be changed directly.
Example program
import java.awt.*;
class LabelDemo1
public static void main(String args[])
Frame f= new Frame(" Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome ");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
Narasimha Murthy G K Page 5
Course II_BCA NEP Syllabus Krupanidhi College
lab2.setBounds(50,100,200,30);
f.add(lab1);
f.add(lab2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
AWT TextField
In Java, AWT contains a TextField Class. It is used for displaying single line text.
TextField Class constructors
import java.awt.*;
class TextFieldDemo1
{
public static void main(String args[])
{
Frame f= new Frame("TextField Demo");
TextField t1,t2;
t1=new TextField("Welcome ");
Narasimha Murthy G K Page 6
Course II_BCA NEP Syllabus Krupanidhi College
t1.setBounds(60,100, 230,40);
t2=new TextField("This tutorial is of Java");
t2.setBounds(60,150, 230,40);
f.add(text1);
f.add(text2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
AWT TextArea
In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.
Narasimha Murthy G K Page 7
Course II_BCA NEP Syllabus Krupanidhi College
Example Program
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame f= new Frame();
TextArea area=new TextArea("Welcome ");
area.setBounds(30,40, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one
option i.e true or false. When the checkbox is checked then its state is "on" (true) else it
is "off"(false).
Narasimha Murthy G K Page 8
Course II_BCA NEP Syllabus Krupanidhi College
Example program
import java.awt.*;
public class CheckboxDemo1
CheckboxDemo1(){
Frame f= new Frame("Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
f.add(ckbox1);
f.add(ckbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
public static void main(String args[])
new CheckboxDemo1();
Narasimha Murthy G K Page 9
Course II_BCA NEP Syllabus Krupanidhi College
AWT List
List class is used to create a list with multiple values, allowing a user to select any of
the values. When a value is selected from List, an ItemEvent is generated, which is
handled by implementing ItemListener interface.
Constructors of List
Example Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ListEx1
{
String [] seasons;
Frame jf;
List list;
Label label1;
ListEx1()
{
jf= new Frame("List");
list= new List(7);
label1 = new Label("Select your favorite sports from the list :");
list.add("Badminton");
list.add("Hockey");
list.add("Tennis");
list.add("Football");
list.add("Cricket");
list.add("Formula One");
list.add("Rugby");
Narasimha Murthy G K Page 10
Course II_BCA NEP Syllabus Krupanidhi College
jf.add(label1);
jf.add(list);
jf.setLayout(new FlowLayout());
jf.setSize(260,220);
jf.setVisible(true);
}
public static void main(String... ar)
{
new ListEx1();
}
Output
Menu bar
A menu bar can be created using MenuBar class.
A menu bar may contain one or multiple menus, and these menus are created
using Menu class.
A menu may contain one of multiple menu items and these menu items are created
using MenuItem class.
Narasimha Murthy G K Page 11
Course II_BCA NEP Syllabus Krupanidhi College
Simple constructors of MenuBar, Menu and MenuItem
Example Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuEx1
{
Frame frame;
MenuBar menuBar;
Menu menu1, menu2;
MenuItem mItem1, mItem2, mItem3, mItem4, mItem5, mItem6,
mItem7;
Button button1, button2, button3;
Dialog d1, d2, d3;
MenuEx1()
{
frame = new Frame("MenuBar, Menu and MenuItems");
//Creating a menu bar
menuBar= new MenuBar();
//Creating first menu
menu1 = new Menu("File");
mItem1 = new MenuItem("New");
mItem2 = new MenuItem("Open");
mItem3 = new MenuItem("Save");
//Adding menu items to the menu
menu1.add(mItem1);
Narasimha Murthy G K Page 12
Course II_BCA NEP Syllabus Krupanidhi College
menu1.add(mItem2);
menu1.add(mItem3);
//Creating a second sub-menu
menu2 = new Menu("Save-as");
mItem5 = new MenuItem(".jpeg");
mItem6 = new MenuItem(".png");
mItem7 = new MenuItem(".pdf");
//Adding menu items to the sub-menu
menu2.add(mItem5);
menu2.add(mItem6);
menu2.add(mItem7);
//Adding the sub-menu to the first menu
menu1.add(menu2);
//Adding our menu to the menu bar
menuBar.add(menu1);
//Adding my menu bar to the frame by calling setMenuBar()
method
frame.setMenuBar(menuBar);
frame.setSize(330,250);
frame.setVisible(true);
}
public static void main(String... ar)
{
new MenuEx1();
}
}
OutPut
Narasimha Murthy G K Page 13
Course II_BCA NEP Syllabus Krupanidhi College
Applet
An applet is a Java program that can be embedded inside a web page to
generate the dynamic content.
It runs inside the browser and works at client side.
Life cycle of an applet
Narasimha Murthy G K Page 14
Course II_BCA NEP Syllabus Krupanidhi College
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
Benefits of java Applet
They are very secure.
It works at client side so less response time.
Applets can be executed by browsers running under different platforms.
HelloWorld.java
Now you have to create an HTML File that Includes the Applet.
Using a text editor, create a file named Hello.html in the same directory that
contains HelloWorld.class.
Narasimha Murthy G K Page 15
Course II_BCA NEP Syllabus Krupanidhi College
Simple example of Applet by appletviewer
Narasimha Murthy G K Page 16
Course II_BCA NEP Syllabus Krupanidhi College
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Narasimha Murthy G K Page 17
Course II_BCA NEP Syllabus Krupanidhi College
Example
GraphicsDemo.java
Narasimha Murthy G K Page 18
Course II_BCA NEP Syllabus Krupanidhi College
Displaying Image in Applet
The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
Other required methods of Applet class to display image:
getCodeBase() Gets the base URL.
getDocumentBase() Gets the URL of the document in which the applet is
embedded.
Narasimha Murthy G K Page 19
Course II_BCA NEP Syllabus Krupanidhi College
Example of displaying image in applet
Myappelt.html
Narasimha Murthy G K Page 20
Course II_BCA NEP Syllabus Krupanidhi College
Event Handling
Event handling has three main components,
Events : An event is a change of state of an object.
Events Source : Event source is an object that generates an event.(producer of an
event)
Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs. Listener is responsible for generating response to an event.
In event Delegation model
Event Listeners Register with the source.
Source Generates the event, makes an event object and send it to the listeners.
Listeners Process the event object and returns
Important Event Class and Listeners Interface are
Narasimha Murthy G K Page 21
Course II_BCA NEP Syllabus Krupanidhi College
ActionEvent and ActionListener
An event of type ActionEvent class is generated when a source such as -
A button is clicked, or,
An item in the list is double-clicked, or,
A menu item is selected in the menu.
The class which processes ActionEvent should implement ActionListener Interface
ActionListner Interface provides method
Example Program
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithButtons extends Applet implements ActionListener {
Narasimha Murthy G K Page 22
Course II_BCA NEP Syllabus Krupanidhi College
Button button1, button2;
public void init() {
button1 = new Button("Button 1");
add(button1);
button1.addActionListener(this);
button2 = new Button("Button 2");
add(button2);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1)
System.out.println("Button 1 was pressed");
else
System.out.println("Button 2 was pressed");
}
MouseEvent and MouseListener
An event of type MouseEvent is generated in a situations when -
A mouse cursor enters a window area.
A mouse cursor exists a window area.
A mouse button is being pressed.
A mouse button is released.
The class which processes MouseEvent t should implement MouseListener
Interface
MouseListener Interface provides the following method
Narasimha Murthy G K Page 23
Course II_BCA NEP Syllabus Krupanidhi College
KeyEvent and KeyListener
An event of type KeyEvent class is generated when a source such as, a key on the
keyboard is pressed in a textfield or in a textarea.
Some methods of KeyEvent class
Narasimha Murthy G K Page 24
Course II_BCA NEP Syllabus Krupanidhi College
The class which processs the keyEvent should implement Key Listener Interface
The method of the keyListner Interface are
Layout Managers
In Java, Layout Managers is an object that determines the way that Components are
arranged in a container
There are several predefined layout manager They are
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. javax.swing.BoxLayou
Narasimha Murthy G K Page 25
Course II_BCA NEP Syllabus Krupanidhi College
java.awt.FlowLayout
The flow layout manager arranges the components one after another from left-to-right
and top-to-bottom manner. The flow layout manager gives some space between
components.
There are 3 types of constructor in the Flow Layout. They are as following:
1. FlowLayout()
2. FlowLayout(int align)
3. FlowLayout(int align, int hgap, int vgap)
The constant align in FlowLayout, may take one of these values
import java.awt.*;
import javax.swing.*;
public class FlowDemo1{
JFrame frame1;
FlowDemo1() {
frame1=new JFrame();
JButton box1=new JButton("1");
JButton box2=new JButton("2");
JButton box3=new JButton("3");
JButton box4=new JButton("4");
JButton box5=new JButton("5");
JButton box6=new JButton("6");
JButton box7=new JButton("7");
JButton box8=new JButton("8");
JButton box9=new JButton("9");
Narasimha Murthy G K Page 26
Course II_BCA NEP Syllabus Krupanidhi College
JButton box10=new JButton("10");
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.add(box10);
frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
frame1.setSize(400,400);
frame1.setVisible(true);
}
public static void main(String[] args)
{
new FlowDemo1();
}
}
Output
BorderLayout
BorderLayout arranges the components in the five regions. Four sides are referred to
as north, south, east, and west. The middle part is called the center. Each region can
Narasimha Murthy G K Page 27
Course II_BCA NEP Syllabus Krupanidhi College
contain only one component and is identified by a corresponding constant
as NORTH, SOUTH, EAST, WEST, and CENTER.
Constructors:
BorderLayout(): It will construct a new borderlayout with no gaps between the
components.
BorderLayout(int, int): It will constructs a border layout with the specified
gaps between the components.
//Java Program illustrating the BorderLayout
import java.awt.*;
import javax.swing.*;
public class border
{
JFrame JF;
border()
{
JF=new JFrame(); //JFrame object
//Lying at top, will be the button named 'North'
JButton b1=new JButton("NORTH");
//Lying at bottom, will be the button named 'South'
JButton b2=new JButton("SOUTH");
//Lying at left, will be the button named 'East'
JButton b3=new JButton("EAST");
//Lying at right, will be the button named 'West'
JButton b4=new JButton("WEST");
//In the center, will be the button named 'Center'
JButton b5=new JButton("CENTER");
//Adding our buttons
JF.add(b1,BorderLayout.NORTH);
JF.add(b2,BorderLayout.SOUTH);
JF.add(b3,BorderLayout.EAST);
JF.add(b4,BorderLayout.WEST);
JF.add(b5,BorderLayout.CENTER);
//Function to set size of the Frame
JF.setSize(300, 300);
//Function to set visible status of the frame
JF.setVisible(true);
}
Narasimha Murthy G K Page 28
Course II_BCA NEP Syllabus Krupanidhi College
//Driver Code
public static void main(String[] args)
{
//Calling the constructor
new border();
}
}
OutPut
Grid Layout
Grid Layout is used, when we want to arrange the components in a rectangular grid.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns along with given horizontal and vertical gaps.
Example Program
import java.awt.*;
import javax.swing.*;
public class GridDemo1{
Narasimha Murthy G K Page 29
Course II_BCA NEP Syllabus Krupanidhi College
JFrame frame1;
GridDemo1(){
frame1=new JFrame();
JButton box1=new JButton("*1*");
JButton box2=new JButton("*2*");
JButton box3=new JButton("*3*");
JButton box4=new JButton("*4*");
JButton box5=new JButton("*5*");
JButton box6=new JButton("*6*");
JButton box7=new JButton("*7*");
JButton box8=new JButton("*8*");
JButton box9=new JButton("*9*");
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);
}
public static void main(String[] args) {
new GridDemo1();
}
}
output
Narasimha Murthy G K Page 30
Course II_BCA NEP Syllabus Krupanidhi College
JavaSwing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
Narasimha Murthy G K Page 31
Course II_BCA NEP Syllabus Krupanidhi College
Narasimha Murthy G K Page 32