0% found this document useful (0 votes)
28 views

Unit-4 Event and GUI Programming

This document covers event and GUI programming in Java, detailing event handling, types of events, and the components of GUI such as panels, frames, and layout managers. It explains the delegation model for event processing, mouse and key events, and introduces various GUI components like buttons, text fields, and checkboxes. Additionally, it provides examples of Java code for creating GUI elements and handling events.

Uploaded by

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

Unit-4 Event and GUI Programming

This document covers event and GUI programming in Java, detailing event handling, types of events, and the components of GUI such as panels, frames, and layout managers. It explains the delegation model for event processing, mouse and key events, and introduces various GUI components like buttons, text fields, and checkboxes. Additionally, it provides examples of Java code for creating GUI elements and handling events.

Uploaded by

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

OOPs Concepts and Programming in Java – NEP 1

UNIT – 4
EVENT AND GUI PROGRAMMING

Syllabus: 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.

EVENT HANDLING IN JAVA


Event handling in Java is the process of controlling an event and taking appropriate action
if one occurs.
Components of Event Handling:
Event handling has three main components,
 Events: An event is a change in state of an object.
 Events Source: Event source is an object that generates an event.
 Listeners: A listener is an object that listens to the event. A listener gets notified
when an event occurs.

How Events are handled?


The modern approach to event processing is based on the Delegation Model. It defines a
standardized and compatible mechanism for generating and processing events.
In this approach, a source generates an event and sends it to one or more listeners. The
listener sits and waits for an event to occur. When it gets an event, it is processed by the
listener and returned. The user interface elements can delegate the processing of an
event to a different function. The image below shows the flow chart of the event
delegation model.

EVENT TYPES

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 2

Event describes the change in state of any object. For Ex: Pressing a button, Entering a
character in Textbox, Clicking or Dragging a mouse, etc.
Events are divided into two major categories:
 Foreground Events: The foreground events are those events that require direct
interaction of the user. These types of events are generated as a result of user
interaction with the GUI component. For example, clicking on a button, mouse
movement, pressing a keyboard key, selecting an option from the list, etc.

 Background Events: The Background events are those events that result from the
interaction of the end-user. For example, an Operating system interrupts system
failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides
control over the events and responses.

MOUSE EVENTS
The user may click, release, drag or move a mouse while interacting with the application
these are the mouse events. To trap the mouse events, MouseListener and
MouseMotionListener interfaces of java.awt.event package are used.
The following methods are being used by MouseListener:

1. void mouseClicked(MouseEvent e): This method is invoked when the button


has been clicked(pressed and released) on a component.
2. void mouseEntered(MouseEvent e): This method is invoked when the
mouse enters a component.
3. void mouseExited(MouseEvent e): This method is invoked when the mouse
exits a component.
4. void mousePressed(MouseEvent e): This method is invoked when the
mouse button has been pressed on a component.
5. void mouseRelease(MouseEvent e): This method is invoked when the
mouse button has been released on a component.

KEY EVENTS
A user interacts with the application by pressing either keys on keyboard or by using
mouse. A programmer must know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed or released. These are also called key events,
knowing these events will enable the programmer to write his code according to the key
pressed or mouse event.
keyListener interface of java.awt.event package helps to know which key is pressed or
released by the user.
It has 3 methods:

1. public void keyPressed(keyEvent ke): This method is called when a key is


pressed on a keyboard. This include any key on the keyboard along with special
keys like function keys like shift, alter, caps lock etc.

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 3

2. public void keyTyped(keyEvent ke): This method is called when a key is


typed on a keyboard. This is same as keyPressed() method but this method is called
when general keys like A to Z or 1 to 9etc are typed. It cannot work with special
keys.

3. public void keyReleased(keyEvent ke): This method is called when the key
is released.

GUI BASICS
AWT stands for Abstract window toolkit is an Application Programming Interface (API) for
creating Graphical User Interface (GUI) in Java. It allows Java programmers to develop
window-based applications.
AWT provides various components like button, label, checkbox, etc. used as objects inside
a Java program.
The following image represents the hierarchy for Java AWT:

Component: Component is an object having a graphical representation that can be


displayed on the screen and that can interact with the user. For examples buttons,
checkboxes, list and scrollbars of a graphical user interface.
Container: Container object is a component that can contain other components like
buttons, textfields, labels etc. Components added to a container are tracked in a list.
Container is a subclass of component class. The classes that extends container are
Window, Frame and Panel.
Window: The window is the container that has no borders and menu bars. You must use
frame, dialog or another window for creating a window.
Panel: The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame: The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.

LAYOUT MANAGERS
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 4

forms. LayoutManager is an interface that is implemented by all the classes of layout


managers.
Commonly used three layouts are:
1. Flow Layout.
2. Border Layout.
3. Grid Layout.

1. Flow Layout:
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.

Constructors of FlowLayout class:


 FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.

 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

2. Boarder Layout:
The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center. Each region (area) may contain one component
only. It is the default layout of a frame or window. The BorderLayout provides
five constants for each region: NORTH, SOUTH, EAST, WEST, CENTER.

Constructors of BorderLayout class:


 BorderLayout(): creates a border layout but with no gaps between the
components.

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 5

 BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

3. Grid Layout:
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class:


 GridLayout(): creates a grid layout with one column per component in a
row.
 GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
 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.

GUI COMPONENTS
GUI components or AWT controls
 Java AWT controls are the components that are used to design GUI or web
applications.
 AWT provides many ready-made and reusable GUI components in package
java.awt.
 The frequently-used are: Button, TextField, Label, Checkbox, Radio buttons, List,
and Choice etc..

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 6

GUI Components List:

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 7

SL Component
Description GUI
No s
A Label object is a component for placing text
1 Label
in a container.

2 Button This class creates a labelled button.

A TextField object is a text component that


3 Text Field
allows for the editing of a single line of text.

A check box is a graphical component that can


4 Check Box be in either an on (true) or off (false) state. It
permit multiple selections.

Radio buttons permit only one element to be


5 Radio Button
selected from the set.

A TextArea object is a text component that


6 Text Area
provides an area to hold multiple lines of text.

A drop down box contains list of items. User


7 Combo box
can select a single item.

A list class is used to represent a list of items


8 List together. User can choose either one item or
multiple items from the list.

The object of Scrollbar class is used to add


9 Scroll bars
horizontal and vertical scrollbar.

JSlider Component allows user to input value


10 Slider by moving an indicator in vertical or horizontal
fashion.

A menu provides a space-saving way to let the


user choose one of several options. It is pull
11 Menu
down menu component which is displayed on
the menubar.

A dialog box is a small graphical window that


12 Dialog Box displays a message to the user or requests
input.

LABELS

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 8

The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly.
Label Declaration:
public class Label extends Component implements Accessible
Ex: Label n = new Label(“Name:”);

Java Program for creating two labels to display text on the frame.

import java.awt.*;
class demo
{
public static void main(String args[])
{
Frame f = new Frame("Label Demo");
Label lab1, lab2;
lab1 = new Label( "Welcome to JAVA World" );
lab1.setBounds(50,50,200,30);
lab2 = new Label("JAVA Programming");
lab2.setBounds(50,100,200,30);
f.add(lab1);
f.add(lab2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

BUTTONS
In Java, AWT contains a Button Class. Push button is used for creating a labelled button
which can perform an action.
When a button is clicked, it generates an ActionEvent which ca be handled using the
ActionListener interface and event handling method is actionPerformed( ).
Button Declaration:
public class Button extends Component implements Accessible
Ex: Button b = new Button(String label);
Java program to create a button and add it to the frame by providing coordinates.
import java.awt.*;

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 9

public class demo


{
public static void main(String[] args)
{
Frame f = new Frame("Button Demo");
Button b = new Button("Press Here");
b.setBounds(80,80,80,50);
f.add(b);
Output:
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}

TEXT FIELD
A TextField or textbox is a single line text entry control which allows the user to enter a
single line of text.
A TextField is a single line area that the user can type into. It is a good way of getting text
input from the user.

TextField Declaration:
public class TextField extends TextComponent
Ex: TextField tf = new TextField(size);

Java program to create a text field and display it on frame.


import java.awt.*;
class demo
{
public static void main(String args[])
{
Frame f = new Frame("TextField Demo");
TextField text1;
text1=new TextField("Welcome to JAVA");
text1.setBounds(60,100, 230,40); Output:

f.add(text1);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 10

TEXT AREA
A TextArea class is used for displaying multi-line text. It is a multiline region that displays
text. It allows the editing of multiple line text.

TextArea Declaration:
public class TextArea extends TextComponent

Ex: TextArea ta = new TextArea(“Type Here”, 5, 50, 3);

Java program to demonstrate TextArea:


import java.awt.*;
public class demo
{
demo()
{
Frame f= new Frame("TextArea Demo");
TextArea area=new TextArea("Welcome to JAVA");
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 demo();
}
}
Output:

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). It permit for multiple selection.

Checkbox Syntax:
public class Checkbox extends Component implements ItemSelectable,
Accessible

Ex: Checkbox cb = new Checkbox(Label);


Java program to demonstrate Checkbox:

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 11

import java.awt.*;
public class demo
{
demo()
{
Frame f= new Frame("Checkbox Demo");
Checkbox cb1 = new Checkbox("C++", true);
cb1.setBounds(100,100, 60,60);
Checkbox cb2= new Checkbox("JAVA”);
cb2.setBounds(100,150, 60,60);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new demo( );
}
}
Output:

RADIO BUTTON
CheckboxGroup enables you to create radio buttons in AWT.
The object of CheckboxGroup class is used to group together a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time. Only one check box
is in "on" state and remaining check box button is in "off" state.
Radio buttons permit only one element to be selected from the set.

CheckboxGroup Declaration:
public class CheckboxGroup extends Object implements Serializable

Ex: CheckboxGroup cbg = new CheckboxGroup( );


Checkbox cb = new Checkbox(Label, cbg, Boolean);

Java program to demonstrate CheckboxGroup (Radio button):


import java.awt.*;

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 12

public class demo


{
demo()
{
Frame f = new Frame("Radio Button Demo");
CheckboxGroup obj = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Yes", obj, true);
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("No", obj, false);
cb2.setBounds(100,150, 50,50);

f.add(cb1);
f.add(cb2);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new demo();
}
}
Output:

COMBO BOX
Combo box or drop down box can be created by using Choice class.
It is used for creating a drop-down menu of choices. When a user selects a particular item
from the drop-down then it is shown on the top of the menu.

Choice Declaration:

public class Choice extends Component implements ItemSelectable, Accessible

Ex: Choice ch = new Choice( );

Java program to demonstrate Combo Box:

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 13

import java.awt.*;
public class demo
{
demo()
{
Frame f = new Frame("Combo Box Demo");
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
f.add(obj);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new demo();
}
}
Output:

LIST
In Java, AWT contains a List Class. It is used to represent a list of items together. One or
more than one item can be selected from the list. More than one items in the list box are
visible to the user.
List Declaration:

public class List extends Component implements ItemSelectable, Accessible

Ex: List l = new List(int, Boolean);

Java program to demonstrate List:

import java.awt.*;
public class demolist

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 14

{
demo()
{
Frame f= new Frame("List Demo");

List obj=new List(6);


obj.setBounds(80,80, 100,100);

obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
f.add(obj);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new demo();
} Output:
}

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

It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.

Scrollbar Declaration:
public class Scrollbar extends Component implements Adjustable, Accessible

Ex: Scrollbar sb = new Scrollbar( );

Java program to demonstrate Scrollbar:

import java.awt.*;
public class demo
{

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 15

demo()
{
Frame f = new Frame("Scrollbar Demo");

Scrollbar s = new Scrollbar( );


s.setBounds (100, 100, 50, 100);
f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String args[])


{
new demo();
}
} Output:

SLIDER
The Java JSlider class is used to create the slider. By using JSlider, a user can select a
value from a specific range.

Slider Declaration:
public class JSlider extends JComponent implements SwingConstants, Accessible

Ex: JSlider slider = new JSlider( );

Java program to demonstrate Slider:

import javax.swing.*;
public class demo extends JFrame
{
demo()
{
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[])
{
demo frame=new demo();
frame.pack();
frame.setVisible(true);
}

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 16

} Output:

MENU
In Java, AWT contains a Menu and MenuItem Class. The menu is used to create a drop-
down of menu components which is displayed from the menu bar. MenuItem is used for
adding Lable in Menu.

Menu Declaration:
public class Menu extends MenuItem implements MenuContainer, Accessible

Ex: Menu menufile = new Menu(“File”);

Java program to demonstrate Menu:


import java.awt.*;
class demo
{
demo()
{
Frame f = new Frame("Menu Demo") ;
MenuBar mb= new MenuBar();
Menu fileMenu = new Menu("File");
mb.add(fileMenu);
MenuItem a1 = new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
fileMenu.add(a1);
fileMenu.add(a2);
fileMenu.add(a3);
Output:
f.setMenuBar(mb);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new demo();
}
}
DIALOG BOX
In Java, AWT contains a Dialog. It is a type of window which is having a border and a title.
But it does not have any maximize and minimize button.

Dialog Box Declaration:


public class Dialog extends Window

Ex: Menu menufile = new Menu(“File”);

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 17

Java program to demonstrate Dialog Box:

import java.awt.*;
import java.awt.event.*;
public class demo
{
private static Dialog d;
demo()
{
Frame f= new Frame();
d = new Dialog(f , "Dialog Demo", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
demo.d.setVisible(false);
}
});
d.add( new Label ("Click on button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new demo();
}
}

Output:

APPLET AND ITS LIFE CYCLE


An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works on the client-side.

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five
core methods namely init(), start(), stop(), paint() and destroy().These methods are
invoked by the browser to execute.

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 18

Different steps of applet life cycle are as follows:

1. Born or Initialization State:


It is the first stage of an applet in the applet life cycle. In this state, Applet enters
the initialization state when it is first loaded. init() method is used to initialize an
applet.
Initialization occurs only, once in the applet’s life cycle.
Syntax: public void init( )
{
// Code to initialize objects
}

2. Running State:
It is the second stage of an applet in the applet life cycle. In this state, the applet
starts running. The start( ) method contains the actual code of the applet that
should run. The start() method executes immediately after the init( ) method.
Syntax: public void start( )
{
// To start the applet code
}

3. Idle State:
It is the third state of an applet in the applet life cycle. In this state, an applet
becomes idle, which means it stopped from running. stop( ) method is used to
stop an applet.
Syntax: public void stop( )
{
// code to stop the applet
}

4. Dead State:
In this state, the applet is removed from memory. destroy( ) method is used to
destroy the applet. This occurs automatically when we quit the browser.
Like initialization, destroying occurs only once in the applet’s life cycle.
Syntax: public void destroy( )
{
// destroy the applet

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 19

5. Display State:
The paint( ) method is used to redraw the output on the applet display area. The
paint() method executes after the execution of start() method and whenever the
applet or browser is resized.
Syntax: public void paint(Graphics graphics)
{
//code to paint any shapes
}

*******

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.


OOPs Concepts and Programming in Java – NEP 20

UNIT – 5
I/O PROGRAMMING
Syllabus: Text and Binary I/O, Binary I/O classes, Object I/O, Random Access Files. Multithreading in java:
Thread life cycle and methods, Runnable interface, Thread synchronization, Exception handling with try catch
finally.

II BSc, III Sem. Dept. of Computer Science, GFGC, Tiptur.

You might also like