0% found this document useful (0 votes)
44 views39 pages

UNIT 5 (OOPs)

Btech cse oops notes

Uploaded by

HIMANSHU SHARMA
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)
44 views39 pages

UNIT 5 (OOPs)

Btech cse oops notes

Uploaded by

HIMANSHU SHARMA
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/ 39

GUI(Graphical User Interface)

GUI is the interface that uses graphical elements to let people interact as per requirement
with electronic devices including computers, laptops, tablets, and smartphones. In terms of
human-computer interaction systems or technology, it’s a very important component of
software application programming since it substitutes actions for the text-based commands
in the system. Whether it’s a text file, object, image, or video as per requirement, it displays
all types of required content a user could envision in the system. Additionally, it can be
featured in the gaming platform
History of GUI
In the year of 1981, Alan Kay, Douglas Engelbart, and other researchers at Xerox PARC (Palo
Alto Research Centre) developed the GUI technology. A GUI-equipped Lisa computer was
later released by Apple as per requirement on January 19, 1983. Before there was a
graphical user interface, communication was done via the command-line interface, or CLI to
manage the overall system. The end users did not find the CLI particularly enjoyable to use
and modify, so they were unfamiliar with all of the user-beneficial commands. One of the
most important features of GUI is “ease of use”. The individual system of Xerox 8010
Information System served as the first GUI-centric machine operating model in the
technology.
Components of GUI
 Pointers: The pointer appears on the user’s screen as a marking symbol. The pointer
moves on to choose instructions and objects as per requirement.
 Icons: Icons allude to tiny visual representations of windows, documents, actions,
and other things on the display screen to simplify. A pointer and pointing device can
be used by the user to carry out the initial tasks for the overall processes.
 Pointing tool: At the initial stages, the pointing tool enables the user to select and
move the required pointer items on the screen, including a trackball or mouse. It is
the most beneficial tool in GUI.
 Desktop: The desktop is the screen that is contained within the icons and user
beneficial.
Advantages of GUI
 A graphical user interface (GUI) is basically seen as more intuitive for users than a
text-based command-line interface as per requirement, such MS-DOS or the Unix-like
operating system shell process.
 It is incredibly user-friendly and readily available to all and for novices, the user
interface is rather easy to understand and uncomplicated as per requirement.
 GUI represents the now-hidden lines of command with the required graphic
elements.
 The end users must commit required instructions to memory for the software to
function properly.

Java Swing
Java Swing is a popular and powerful Graphical User Interface (GUI)
toolkit that is used for developing desktop applications. It is a part of
the Java Foundation Classes (JFC) and provides a rich set of
components and layout managers for creating a variety of GUIs. Java
Swing is platform-independent and can be used on any operating
system that supports Java.

It provides a set of lightweight components that are not only easy to


use but also customizable. Some of the commonly used components
in Swing are buttons, text fields, labels, menus, and many more.

Java Swing provides a pluggable look and feels that allows developers
to customize the GUI according to the user’s preferences. It also
provides a robust event-handling mechanism that allows developers to
handle events generated by the graphical components.

Some of the commonly used layout managers in Java Swing are


BorderLayout, FlowLayout, GridLayout, CardLayout, and BoxLayout.
These layout managers allow developers to create complex and
intuitive GUIs that are easy to use and navigate.

Features of Java Swing

Some of the notable features of Java Swing are:

1. Platform Independence: Platform independence is one of Java


Swing’s most remarkable features. It can run on any platform that
supports Java. Thus, Swing-based applications can run on Windows,
Mac, Linux, or any other Java-compatible operating system.
2. Lightweight Components: Java Swing provides a set of
lightweight components that are easy to use and customizable.
These components are designed to consume less memory and use
less processing power, making Swing-based applications run
efficiently.
3. Pluggable Look and Feel: Java Swing provides a pluggable look
and feels that allows developers to customize the appearance of the
GUI according to the user’s preferences. Developers can choose
from several pre-built looks and feel themes or create their own
custom themes.
4. Layout Managers: Java Swing provides a set of layout managers
that can be used to organize the graphical components in a GUI.
These layout managers enable developers to create flexible and
responsive GUIs that adapt to different screen sizes and resolutions.

5. Robust Event Handling Mechanism: Java Swing provides a


robust event handling mechanism that allows developers to handle
events generated by the graphical components. Developers can
register event listeners to detect and respond to user interactions
with the GUI.

Java Swing Class Hierarchy

Java Swing Packages

Some of the commonly used packages in Java Swing are:

1. javax.swing: This package contains the core components of Swing,


such as JButton, JLabel, JTable, JList, and many more. It also contains
the classes for creating top-level containers such as JFrame and
JDialog.

2. javax.swing.event: This package contains the classes for handling


events generated by the Swing components. It includes event
listener interfaces, event adapter classes, and event objects.
3. javax.swing.border: This package contains classes for creating
borders around the Swing components. It includes the classes for
creating line borders, etched borders, and titled borders.

4. javax.swing.layout: This package contains the classes for creating


and managing layout managers in Swing. It includes the commonly
used layout managers such as BorderLayout, FlowLayout,
GridLayout, BoxLayout, and CardLayout.

5. javax.swing.plaf: This package contains the classes for the


pluggable look and feels feature of Swing. It includes the classes for
creating and managing the look and feel themes, and also provides
the default look and feel theme for each platform.

6. javax.swing.text: This package contains the classes for creating


and managing text components in Swing. It includes classes for
creating text fields, text areas, and other text-related components.

7. javax.swing.table: This package contains the classes for creating


and managing tables in Swing. It includes the classes for creating
JTable, TableModel, TableColumn, and TableCellRenderer.

Components of Java Swing

1. JFrame
2. JButton
3. JLabel
4. JTextField
5. CheckBox
6. JList
7. JTable
8. JTextArea
9. JPasswordField

10. JScrollPane

11. JRadioButton

12. JComboBox
1. JFrame: JFrame is a top-level container that represents the main
window of a GUI application. It provides a title bar, and minimizes,
maximizes, and closes buttons.

A program to change background color of a frame

import java.awt.*; //importing awt package

import javax.swing.*; //importing swing package

import java.awt.event.*; //importing event package

//For an event to occur upon clicking the button, ActionListener interface


should be implemented

class StColor extends JFrame implements ActionListener{

JFrame frame;

JPanel panel;

JButton b1,b2,b3,b4,b5;

StColor(){

frame = new JFrame("COLORS");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel(); //Creating a panel which is a container and will


hold all the buttons

panel.setSize(100, 50);
b1 = new JButton("BLUE"); //Creating a button named BLUE

b1.addActionListener(this); //Registering the button with the listener

b2 = new JButton("RED"); //Creating a button named RED

b2.addActionListener(this); //Registering the button with the listener

b3 = new JButton("CYAN");//Creating a button named CYAN

b3.addActionListener(this);//Registering the button with the listener

b4 = new JButton("PINK"); //Creating a button named PINK

b4.addActionListener(this); //Registering the button with the listener

b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA

b5.addActionListener(this); //Registering the button with the listener

//Adding buttons to the Panel

panel.add(b1);

panel.add(b2);

panel.add(b3);

panel.add(b4);
panel.add(b5);

frame.getContentPane().add(panel); //adding panel to the frame

frame.setSize(500,300);

frame.setVisible(true);

frame.setLayout(new FlowLayout());

//The below method is called whenever a button is clicked

@Override

public void actionPerformed(ActionEvent e) {

//This method returns an object of the button on which the Event-

Pressing of button initially occurred

Object see = e.getSource();

if(see ==(b1)){ //Checking if the object returned is of button1

frame.getContentPane().setBackground(java.awt.Color.blue);
//changing the panel color to blue

if(see == b2){ //Checking if the object returned is of button2

frame.getContentPane().setBackground(java.awt.Color.red);
//changing the panel color to red
}

if(see == b3){ //Checking if the object returned is of button3

frame.getContentPane().setBackground(java.awt.Color.cyan);//changing
the panel color to cyan

if(see == b4){ //Checking if the object returned is of button4

frame.getContentPane().setBackground(java.awt.Color.pink);
//changing the panel color to pink

if(see == b5){ //Checking if the object returned is of button5

frame.getContentPane().setBackground(java.awt.Color.magenta);
//changing the panel color to magenta

class Test {

public static void main(String[] args) {

StColor o = new StColor();

Output
2. JButton: JButton is a component that represents a clickable
buttonJButton class provides functionality of a button. It is used to
create button component. JButton class has three constuctors,

Program :In this example, we are creating two buttons using


Jbutton class and adding them into Jframe container.

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class testswing extends JFrame

testswing()

JButton bt1 = new JButton("Yes"); //Creating a Yes Button.

JButton bt2 = new JButton("No"); //Creating a No Button.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close


operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object

setSize(400, 400); //setting size of Jframe

add(bt1); //adding Yes button to frame.

add(bt2); //adding No button to frame.

setVisible(true);

public static void main(String[] args)

new testswing();

Output
3. JLabel: JLabel is a component that displays text or an image. It is
commonly used to provide information or to label other
components.In Java, Swingtoolkit contains a JLabel Class. It is under
package javax.swing.JLabel class. It is used for placing text in a box.
Only Single line text is allowed and the text can not be changed
directly.

The JLabel Contains 4 constructors. They are as following:

1. JLabel()

2. JLabel(String s)

3. JLabel(Icon i)

4. JLabel(String s, Icon i, int horizontalAlignment)

import javax.swing.*;

class SLabelDemo1
{

public static void main(String args[])

JFrame label_f= new JFrame("studytonight ==> Label Demo");

JLabel label_l1,label_l2;

label_l1=new JLabel("Welcome to studytonight.com");

label_l1.setBounds(50,50, 200,30);

label_l2=new JLabel("How are You?");

label_l2.setBounds(50,100, 200,30);

label_f.add(label_l1);

label_f.add(label_l2);

label_f.setSize(300,300);

label_f.setLayout(null);

label_f.setVisible(true);

}
4. JTextField: JTextField is a component that allows the user to input
text. It is commonly used to get input from the user, such as a name
or an address. It is used for taking input of single line of text. It is most
widely used text component. It has three constructors,

JTextField(int cols)

JTextField(String str, int cols)

JTextField(String str)

Copy

cols represent the number of columns in text field.

Program

In this example, we are creating text field using JtextField class and
adding into the jframe container.

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class MyTextField extends JFrame

{
public MyTextField()

JTextField jtf = new JTextField(20); //creating JTextField.

add(jtf); //adding JTextField to frame.

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new MyTextField();

Output
5. JCheckBox: JCheckBox is a component that represents a checkbox. It
is commonly used to get a binary input from the user, such as
whether or not to enable a feature.

The JcheckBox class is used to create chekbox in swing framework. In


this example, we are creating three checkboxes to get user response.

JCheckBox(String str)

Program

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends JFrame

public Test()
{

JCheckBox jcb = new JCheckBox("yes"); //creating


JCheckBox.

add(jcb); //adding JCheckBox to frame.

jcb = new JCheckBox("no"); //creating JCheckBox.

add(jcb); //adding JCheckBox to frame.

jcb = new JCheckBox("maybe"); //creating JCheckBox.

add(jcb); //adding JCheckBox to frame.

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new Test();

Output
6. JList: JList is a component that represents a list of elements. It is
typically used to display a list of options from which the user can
select one or more items. In Java, Swing toolkit contains a JList Class.
It is under package javax.swing.JList class. It is used to represent a list
of items together. One or more than one item can be selected from
the list.

The JListContains 3 constructors. They are as following:

1. JList()

2. JList(ary[] listData)

3. JList(ListModel<ary> dataModel)

Program

import javax.swing.*;

public class SListDemo

SListDemo()

JFrame list_f= new JFrame();


DefaultListModel<String> list_l1 = new
DefaultListModel<>();

list_l1.addElement("Red");

list_l1.addElement("Pink");

list_l1.addElement("Blue");

list_l1.addElement("Black");

JList<String> list1 = new JList<>(list_l1);

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

list_f.add(list1);

list_f.setSize(400,400);

list_f.setLayout(null);

list_f.setVisible(true);

public static void main(String args[])

new SListDemo();

}
7. JTable: JTable is a component that represents a data table. It is
typically used to present data in a tabular fashion, such as a list of
products or a list of orders.

In Java, Swing toolkit contains a JTable Class. It is under package


javax.swing.JTable class. It used to draw a table to display data.

The JTableContains 2 constructors. They are as following:

1. JTable()

2. JTable(Object[][] rows, Object[] columns)

Program:In this we create a table using Jtable class and then add it to
the Jframe container.

import javax.swing.*;

public class STableDemo1

JFrame table_f;

STableDemo1(){
table_f=new JFrame();

String table_data[][]={ {"1001","Cherry"}, {"1002","Candy"},


{"1003","Coco"}};

String table_column[]={"SID","SNAME"};

JTable table_jt=new JTable(table_data,table_column);

table_jt.setBounds(30,40,200,300);

JScrollPane table_sp=new JScrollPane(table_jt);

table_f.add(table_sp);

table_f.setSize(300,400);

table_f.setVisible(true);

public static void main(String[] args)

new STableDemo1();

Output
8. JTextArea

In Java, Swing toolkit contains a JTextArea Class. It is under package


javax.swing.JTextArea class. It is used for displaying multiple-line text.

The JTextArea Contains 4 constructors. They are as following:

1. JTextArea()

2. JTextArea(String s)

3. JTextArea(int row, int column)

4. JTextArea(String s, int row, int column)

Program

Lets take an example to create text area in swing. We are using


JtextArea class to create text area and adding to Jframe container.

import javax.swing.*;

public class STextAreaDemo1

{
STextAreaDemo1()

JFrame textArea_f= new JFrame();

JTextArea textArea_area=new JTextArea("Welcome to


studytonight.com ");

textArea_area.setBounds(10,30, 200,200);

textArea_f.add(textArea_area);

textArea_f.setSize(400,400);

textArea_f.setLayout(null);

textArea_f.setVisible(true);

public static void main(String args[])

new STextAreaDemo1();

Output
9. JPasswordField

In Java, Swing toolkit contains a JPasswordField Class. It is under


package javax.swing.JPasswordField class. It is specifically used for
password and it can be edited.

The JPasswordFieldContains 4 constructors. They are as


following:

1. JPasswordField()

2. JPasswordField(int columns)

3. JPasswordField(String text)

4. JPasswordField(String text, int columns)

Program: To generate a password component, swing provides


Jpasswordfield that takes user input in encrypted format.
import javax.swing.*;

public class SPasswordFieldDemo1

public static void main(String[] args)

JFrame passWord_f=new JFrame("studytonight ==> Password Field


Demo");

JPasswordField passWord_value = new JPasswordField();

JLabel passWord_l1=new JLabel("Password ");

passWord_l1.setBounds(20,100, 100,30);

passWord_value.setBounds(100,100,100,30);

passWord_f.add(passWord_value);

passWord_f.add(passWord_l1);

passWord_f.setSize(300,300);

passWord_f.setLayout(null);

passWord_f.setVisible(true);

Output
10. JScrollPane: JScrollPane is a component that provides scrolling
functionality to other components. It is commonly used to add
scrolling to a panel or a table.JRadioButton

11. Radio button:Radio button is a group of related button in which


only one can be selected. JRadioButton class is used to create a radio
button in Frames. Following is the constructor for JRadioButton,

JRadioButton(String str)

Example using JRadioButton

To create radio button in swing, we used jradiobutton class. It is used


to get single user response at a time.

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends JFrame

public Test()
{

JRadioButton jcb = new JRadioButton("A"); //creating


JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("B"); //creating JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("C"); //creating JRadioButton.

add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("none");

add(jcb);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new Test();

Output:
12. JComboBox:Combo box is a combination of text fields and drop-
down list.JComboBox component is used to create a combo box in
Swing. Following is the constructor for JComboBox,

JComboBox(String arr[])

Copy

Example using JComboBox

Lets create an example to add combobox to the jframe . Combo box is


used to create a drop-down menu. See the below example.

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends JFrame

String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.

public Test()

JComboBox jc = new JComboBox(name); //initialzing combo box


with list of name.

add(jc); //adding JComboBox to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new Test();

Output

Advantages of Java Swing

Java Swing provides a number of advantages for developing graphical


user interfaces (GUIs) in Java. Some of the key advantages of Java
Swing are

1. Platform Independence: Swing is written entirely in Java, which


makes it platform-independent. It can run on any platform that
supports Java, without any modification.
2. Look and Feel: Java Swing provides a pluggable look and feels
feature, which allows developers to customize the appearance of
the components. It provides a consistent look and feels across
platforms, which helps in creating a professional-looking GUI.

3. Rich Component Set: Java Swing provides a rich set of


components, including advanced components like JTree, JTable, and
JSpinner. It also provides support for multimedia components, such
as audio and video.

4. Layout Managers: Java Swing provides a variety of layout


managers, which makes it easy to arrange the components on a
GUI. The layout managers help in creating GUIs that are visually
appealing and easy to use.

5. Event Handling: Java Swing provides a powerful and flexible event


handling model, which makes it easy to handle user events such as
mouse clicks and keyboard presses. The event-handling model
makes it easy to add interactivity to the GUI.

6. Customizable: Java Swing components are highly customizable,


which makes it easy to create GUIs that meet the specific needs of
an application. The components can be easily modified to suit the
look and feel of the application.

Disadvantages of Java Swing

Some of the main disadvantages of Java Swing are:

1. Performance: Java Swing applications can be slower than native


applications because of the overhead of running the Java Virtual
Machine (JVM). This can be particularly noticeable in complex
applications with large amounts of data.

2. Look and Feel: While Swing’s pluggable look and feel feature
allows for customization of the components, it can be difficult to
achieve a truly native look and feel. This can make Swing
applications look and feel different from other native applications on
the same platform, which can be confusing for users.

3. Learning Curve: While Swing is easy to learn for developers who


are already familiar with Java, it can be difficult for beginners who
are not familiar with the language. The complex hierarchy of
components and layout managers can also make it difficult to create
complex GUIs.

4. Resource Consumption: Java Swing applications often requires a


significant amount of system resources, such as memory and
computing power. This can be an issue for low-end devices with
limited resources or large-scale apps with a big number of users.
5. Lack of Mobile Support: Since Java Swing is a desktop-oriented
GUI toolkit, it does not support mobile devices well. This could pose
a potential challenge for developers who want to create cross-
platform apps that work on both desktop and mobile platforms.

 container :A container holds a group of components. It


provides a space where a component can be managed and
displayed. Containers are of two types:
1. Top level Containers

o It inherits Component and Container of AWT.

o It cannot be contained within other containers.

o Heavyweight.

o Example: JFrame, JDialog, JApplet

2. Lightweight Containers

o It inherits JComponent class.

o It is a general purpose container.

o It can be used to organize related components together.

o Example: JPanel


JPanel: JPanel is a container that can hold other
components. It is commonly used to group related components
together.

The main task of JPanel is to organize components, various layouts can


be set in JPanel which provide better organization of components,
however, it does not have a title bar.

Constructors of JPanel

1. JPanel(): creates a new panel with a flow layout

2. JPanel(LayoutManager l): creates a new JPanel with specified


layoutManager

3. JPanel(boolean isDoubleBuffered): creates a new JPanel with a


specified buffering strategy

4. JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new


JPanel with specified layoutManager and a specified buffering
strategy

Commonly used Functions of JPanel

1. add(Component c): Adds a component to a specified container

2. setLayout(LayoutManager l): sets the layout of the container to the


specified layout manager

3. updateUI(): resets the UI property with a value from the current look
and feel.

4. setUI(PanelUI ui): sets the look and feel of an object that renders
this component.

5. getUI(): returns the look and feel object that renders this
component.

6. paramString(): returns a string representation of this JPanel.

7. getUIClassID(): returns the name of the Look and feel class that
renders this component.

8. getAccessibleContext(): gets the AccessibleContext associated with


this JPanel.

Let us take a sample program in order to illustrate the use of JPanel class
// Java Program to Create a Simple JPanel
// and Adding Components to it

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Class 1
// Helper class extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2;

// Label to display text


static JLabel l;

// Main class
public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");

// Creating a panel to add buttons


JPanel p = new JPanel();

// Adding buttons and textfield to panel


// using add() method
p.add(b);
p.add(b1);
p.add(b2);
p.add(l);

// setbackground of panel
p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}
Output

Look and Feel in java swing:Swing provides platform specific Look and
Feel. Initially there were very few options for colors and other settings in Java Swing,
that made the entire application look boring and monotonous. With the growth in
Java framework, new changes were introduced to make the UI better and thus giving
developer opportunity to enhance the look of a Java Swing Application.
 Look refers to the appearance of GUI widgets.
 Feel refers to the way the widgets behave.
Sun’s JRE provides the following L&Fs:
1. CrossPlatformLookAndFeel: this is the “Java L&F” also known as “Metal” that looks
the same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the
default.
2. SystemLookAndFeel: here, the application uses the L&F that is default to the system
it is running on. The System L&F is determined at runtime, where the application asks
the system to return the name of the appropriate L&F. For Linux and Solaris, the
System L&Fs are “GTK+” if GTK+ 2.2 or later is installed, “Motif” otherwise. For
Windows, the System L&F is “Windows”.
3. Synth: the basis for creating your own look and feel with an XML file.
4. Multiplexing: a way to have the UI methods delegate to a number of different look
and feel implementations at the same time.
We can use UIManager to load the L&F class directly from classpath.
For which the code goes like this:
UIManager.setLookAndFeel("fully qualified name of look and feel");
Event:Change in the state of an object is known as Event, i.e., event describes the
change in the state of the source. Events are generated as a result of user interaction
with the graphical user interface components. For example, clicking on a button,
moving the mouse, entering a character through keyboard, selecting an item from
the list, and scrolling the page are the activities that causes an event to occur.
Types of Event
The events can be broadly classified into two categories −
 Foreground Events − These events require direct interaction of the user. They are
generated as consequences of a person interacting with the graphical components in
the Graphical User Interface. For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from list, scrolling the page,
etc.
 Background Events − These events require the interaction of the end user. Operating
system interrupts, hardware or software failure, timer expiration, and operation
completion are some examples of background events.

Event Handling:Event Handling is the mechanism that controls the event


and decides what should happen if an event occurs. This mechanism has a
code which is known as an event handler, that is executed when an event
occurs.

Java uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.

The Delegation Event Model has the following key participants.

 Source − The source is an object on which the event occurs. Source is


responsible for providing information of the occurred event to it's
handler. Java provide us with classes for the source object.
 Listener − It is also known as event handler. The listener is
responsible for generating a response to an event. From the point of
view of Java implementation, the listener is also an object. The listener
waits till it receives an event. Once the event is received, the listener
processes the event and then returns.
Steps Involved in Event Handling
Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and
information about the source and the event get populated within the same
object.
Step 3 − Event object is forwarded to the method of the registered listener
class.
Step 4 − The method is gets executed and returns.
Event Listner:In Java, an event listener is an interface that handles
events generated by user interactions, such as clicking a button or
moving the mouse. Event listeners are part of the Java event handling
mechanism, which is based on the delegation event model.

Here’s a basic overview of how event listeners work in Java:

1. Event Source: This is the object that generates an event. For example, a
button can be an event source.
2. Event Object: When an event occurs, an event object is created. This
object contains information about the event.
3. Event Listener: This is an interface that defines methods to handle
specific types of events. For example, ActionListener is used to handle
action events like button clicks.

Example of an Event Listener


Here’s a simple example of how to use an ActionListener with a button in a
Java Swing application:
import javax.swing.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");

// Registering the event listener


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new java.awt.FlowLayout());
frame.add(button);
frame.setVisible(true);
}
}

In this example:

 The button.addActionListener method registers an


anonymous ActionListener to the button.
 When the button is clicked, the actionPerformed method is called, and a message
is printed to the console.

Common Event Listener Interfaces


Java provides several event listener interfaces, including:

 ActionListener for action events (e.g., button clicks)


 MouseListener for mouse events (e.g., clicks, enters, exits)
 KeyListener for keyboard events (e.g., key presses)

Each of these interfaces has methods that must be implemented to


handle the respective events
Scala: scala is a general-purpose, high-level, multi-paradigm
programming language. It is a pure object-oriented programming
language which also provides the support to the functional programming
approach. There is no concept of primitive data as everything is an
object in Scala. Scala was designed by the Martin Odersky, professor of
programming methods at École Polytechnique Fédérale de Lausanne
(EPFL) in Switzerland and a German computer scientist.

Why scala?
Scala has many reasons for being popular among programmers.
 Easy to Start: Scala is a high level language so it is closer to other
popular programming languages like Java, C, C++. Thus it becomes
very easy to learn Scala for anyone. For Java programmers, Scala is
more easy to learn.
 Contains best Features: Scala contains the features of different
languages like C, C++, Java, etc. which makes the it more useful,
scalable and productive.
 Close integration with Java: The source code of the Scala is
designed in such a way that its compiler can interpret the Java
classes. Also, Its compiler can utilize the frameworks, Java Libraries,
and tools etc. After compilation, Scala programs can run on JVM.
 Web – Based & Desktop Application Development: For the web
applications it provides the support by compiling to JavaScript.
Similarly for desktop applications, it can be compiled to JVM bytecode.
 Used by Big Companies: Most of the popular companies like Apple,
Twitter, Walmart, Google etc. move their most of codes to Scala from
some other languages, reason being it is highly scalable and can be
used in backend operations.
Note-People always thinks that Scala is a extension of Java. But it is not
true. It is just completely interoperable with Java. Scala programs get
converted into .class file which contains Java Byte Code after the
successful compilation and then can run on JVM
Example : A simple program to print Hello world! Using scala( object-
oriented approach).

Object HelloWorld{
Def main(args:Array[String]){
Println(“Hello world”);
}
}
Output:
Hello world
Explaination-
object HelloWorld: object is the keyword which is used to create the
objects. Here “HelloWorld” is the name of the object.
def main(args: Array[String]): def is the keyword in Scala which is
used to define the function and “main” is the name of Main
Method. args: Array[String] are used for the command line arguments.
println(“Hello, Geeks!”): println is a method in Scala which is used to
display the string on console.

Advantages
 Object- Oriented: Every value in Scala is an object so it is
a purely object-oriented programming language. The behavior and
type of objects are depicted by the classes and traits in Scala.
 Functional: It is also a functional programming language as every
function is a value and every value is an object. It provides the
support for the high-order functions, nested functions, anonymous
functions, etc.
 Statically Typed: The process of verifying and enforcing the
constraints of types is done at compile time in Scala. Unlike other
statically typed programming languages like C++, C, etc., Scala
doesn’t expect the redundant type information from the user. In most
cases, the user has no need to specify a type.
 Extensible: New language constructs can be added to Scala in form
of libraries. Scala is designed to interpolate with the JRE(Java Runtime
Environment).
 Concurrent & Synchronize Processing: Scala allows the user to
write the codes in an immutable manner that makes it easy to apply
the parallelism(Synchronize) and concurrency.
 Run on JVM & Can Execute Java Code: Java and Scala have a
common runtime environment. So the user can easily move from Java
to Scala. The Scala compiler compiles the program into .class file,
containing the Bytecode that can be executed by JVM. All the classes
of Java SDK can be used by Scala. With the help of Scala user can
customize the Java classes.

Disadvantages
 Sometimes, two approaches make the Scala hard to understand.
 There is a limited number of Scala developers available in comparison
to Java developers.
 It has no true-tail recursive optimization as it runs on JVM.
 It always revolves around the object-oriented concept because every
function is value and every value is an object in Scala.

You might also like