0% found this document useful (0 votes)
34 views140 pages

CUI vs GUI in Java Programming

about swings

Uploaded by

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

CUI vs GUI in Java Programming

about swings

Uploaded by

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

UNIT - V

GUI Programming with Swing – Introduction, limitations of AWT, MVC


architecture, components, containers. Understanding Layout Managers, Flow Layout,
Border Layout, Grid Layout, Card Layout, Grid Bag Layout.

Event Handling- The Delegation event model- Events, Event sources, Event
Listeners, Event classes, Handling mouse and keyboard events, Adapter classes, Inner
classes, Anonymous Inner classes.

A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets
and Applications, passing parameters to applets. Creating a Swing Applet, Painting in
Swing, A Paint example, Exploring Swing Controls- JLabel and Image Icon, JText Field,
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed
Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
Any user interact with java program in two different way
•CUI (Command user Interface)
•GUI (Graphical user Interface)
CUI:If any user interact with java program by passing same commands through command
prompt is known as CUI,
GUI:The environment where the user can interact with an application through graphics or
images is called GUI
Advantages GUI:
It is user Friendly.The user Need not worry about any commands.
It adds attraction and beauty to any application by adding picture,colors,menus,animation.
It is possible to simulate the real life objects using GUI.
For Ex: a calculator program display real calculator on the Screen.
What is AWT?
AWT:
• AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI
(Graphical User Interface) or window-based applications in Java. It was developed by heavily Sun
Microsystems In 1995.
• The java.awt package contains classes and interfaces to develop GUI so that users can interact
more friendly with the applications.
• The java.awt package contains component classes such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
• AWT components are platform-dependent.
• For example an AWT GUI having a button would have a different look and feel across platforms
like windows, Mac OS & Unix
• AWT components are heavy weight .

Note:
Every AWT component depends on the files of local OS to create GUI.This increases the overhead on
the JVM this is the reason AWT components are heavy weight.
Limitations of AWT:Dis-advantages

1. Awt components are heavy weight.


2. AWT Components are platform dependent.

3. The AWT programs increase the overhead on the JVM.Because They depend on files of local
operating system in creating GUI.

4. The button does not support pictures.

5. tables and trees these important components are missing. They are commonly used in
desktop applications.
What is Swing?
Swing is the part of JFC (Java Foundation Classes) built on the top of AWT and
written entirely in Java.
Swing is an API for Java programs that provide GUI. It is used to create window-based applications.
The javax.swing package provides all the component classes like JButton,
JTextField, JCheckbox, Jmenu and JRadiobutton.
• Swing provides platform-independent and lightweight components.
• Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-
drop support.

• Swing is a Set Of API ( API- Set Of Classes and Interfaces ).


•Swing can be used to Develop The Standalone swing GUI Apps Also as Servlets
And Applets
•Swing Follows MVC architecture
•Swing Supports a Pluggable look and feels And Swing provides more powerful
components
What is JFC
• The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
• Java Foundation classes represent a class library developed in java which is an extension to
awt.
• It contains classes that are completely portable,since the entire JFC is developed in pure Java.
• JFC Components are light weight.It utilize min System resources.
• JFC Components have same look and Feel on all plattforms.
• JFC offers a rich set of Components with lot of features this is the reason JFC is very popular
all over the world.
Swing Features or characteristics

Light Weight: Swing components are lightweight. The swing components are completely
developed using java code.

Platform Independent: Swing Components are Platform Independent.

Rich Controls: Swing provides a rich set of advanced controls like Tree, TabbedPane, slider,
colorpicker, and table controls.

Highly Customizable: Swing controls can be customized in a very easy way as visual apperance is
independent of internal representation.

Pluggable look-and feel: Swing based GUI Application look and feel can be changed at run time
based on available values.
Swing Class Hirarchy
Difference Between AWT and SWING
Swing classes :
Object: All classes in Java are inherited from the object class.
Component:A component is an object having a Graphical Representation That can be displayed
on the Screen.
Example of components:Buttons,Labels,CheckBoxes TextFields, RadioButtons, etc. are called
components in Java.
Container:The Container is a component in AWT that can contain other components.A container
is like a screen where in we are placing components like buttons, text fields, checkbox etc.
Ex: Jframe and JPanel.
Swing Components:
JLabel: It inherits JComponent class. It is used for placing text in a container.
JButton: It is used to create a labelled button. It is useful to perform some action when the
button is clicked. It inherits the AbstractButton class and is platform-independent.
JTextField: It inherits the JTextComponent class where the user can type single line of text
JTextArea: It inherits the JTextComponent class where user can enter multiple lines of text.
JList: It inherits JComponent class, the JList represents the user a list of text items.
JScrollBar: It is used to add scroll bar, both horizontal and vertical.
JComboBox Class: It inherits the JComponent class and is used to select a value from a drop-
down list. You can choose one and only one element from the list.
JCheckbox: JCheckBox is used to create a checkbox, of which multiple checkboxes could be
selected at the same time
The user can select one or more options from a group of checkboxes.
JRadioButton: RadioButton is used to select one option from multiple Options. Only one
RadioButton selected at a time.
JSlider
JSlider is a component that lets the users select a value by sliding a knob within a specified
interval.
JTable
JTable is used to create a regular two-dimensional table. The table can display data inside of it.
In addition, the user can also edit the data.
JMenu Class: It inherits the JMenuItem class, and is a pull down menu component which is
displayed from the menu bar.
Ex:
We have a File menu, which includes of save, quit submenu, and Edit menu, including copy, cut,
paste submenu, and Help menu
JPasswordField : A JPasswordField object it is a text component specialized for password entry
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another


component.
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the component.
It is by default false.
Swing Containers
A container holds a group of components. It provides a space where a component can be
managed and displayed.
we can add components like JTextfield, JButton, Jcheckbox etc.
There four Container they are : JPanel, JFrame and Jwindow and JDialog.
1.Jpanel :JPanel is a container that can store a group of components.It is lightweight container
we can use Panels to partition the JFrame. Each panel groups several other components inside it.
A JFrame can have more than one-JPanel and we can add components inside it .
2JFrame: A JFrame is a top-level window with a title ,menubar and a border.It is heavy weight
container
JFrame works like the main window where components like JLabels, JButtons, JTextfields are
added to create a GUI.
3 JWindow: JWindow is a low level container and light weight container, by default it uses
the BorderLayoutwith no borders no menubar and no title.
4. JDialog :The JDialog control represents a top level window with a border
and a title used to take some form of input from the user.
Creating a JFrame
There are two ways to create a JFrame in Swing
1.By creating the Object of JFrame class.
2.By extending JFrame class.
2.By extending JFrame class.
Layout Manager:
Layout Manager:
• A Layout Manager is an object that controls size and position (layout) of components inside
container.
• The LayoutManagers are used to arrange components in a particular manner in a frame or
container.
Container Ex: Window,JFrame etc.
The Following classes represent the layout managers in java
1.FlowLayout
2.BorderLayout
3.CardLayout
4.GridLayout
5.GridBagLayout
6.BoxLayout
The above classes are present in the java.awt package
BoxLayout is present in the Javax.swing package
1.FlowLayout is useful to arrange the components in a line or Sequence one after
other. It is the Default Layout of the Applet or Panel.
The FlowLayout arranges the components in a directional flow, either from left to
right or from right to left.
To create FlowLayout we use the following ways:
FlowLayout f=new FlowLayout();
creates a flow layout with the given alignment and the given
horizontal and vertical gap.
FlowLayout f=new FlowLayout(int alignment)
FlowLayout f=new FlowLayout(int alignment, int hgap,int vgap)
Ex: To arrange From left to right:
JFrame f=new JFrame();
2. BorderLayout:
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 Top border is specified as “North” , and The right border is specified as “ East”.
The Button is specified as “South” , and The left border is specified as “West”.
The center is represented as “Center”.
To create BorderLayout we use the following ways:
BorderLayout f=new BorderLayout();
creates a border layout but with no gaps between the components.
BorderLayout f=new BorderLayout(int hgap,int vgap)
Here hgap and vgap space between components.
3.GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle. The container is divided in to
equal-sized rectangles.
The GridLayout is used to divide the Container in two-dimensional grid form that contains several
rows and colums.
To create GridLayout we use the following ways:
 GridLayout obj=new GridLayout();
creates a grid layout with one column per component in a row.
 GridLayout obj=new GridLayout(int rows, int columns)
creates a grid layout with the given rows and columns but no gaps between
the components.
 GridLayout obj=new GridLayout(int rows, int columns, int horizontalGap, int verticalGap)
4.CardLayout: Card Layout is used, when we want to see only one component at a time. It
treats each component as a card that is why it is known as CardLayout.
The container acts as a stack of cards.

To create CardLayout we use the following ways:

CardLayout c=new CardLayout();

creates a card layout with zero horizontal and vertical gap.

CardLayout c=new CardLayout (int hgap,int vgap)

While adding components to the container we can use add() as

Syntax:

c.add(“cardname” ,component);
To retrieve the components one by one the following methods can be used.

 void first(Container) : to retrieve the first card.


 void last(Container) : to retrieve the last card.
 void next(Container) : to go to the next card.
 void previous(Container) : to go back to previous card.
 Void show(Container,”cardname”): to see the particular card with the name specified.
5.GridBagLayout:GridBagLayout is a more flexible layout manager which allows the components
to be arranged in rows and colums. GridBagLayout class is used to align
components vertically, horizontally.
• The components may not be of the same size
• Each component occupies one or more cells known as its display
area
• With the help of constraints object we arrange component's display area on the grid.
To create GridBagLayout we use the following ways:
GridBagLayout obj=new GridBagLayout();
To apply some constraints on the components, we should first
create an object to GridBagConstraints class as
GridBagConstraints cons=new GridBagConstraints();
1.gridx and gridy
They represent the row and column positions of the component at upper left corner of the
component.
2. gridwidth and gridheight
They specify the number of columns for (gridwidth) or rows for (gridheight) in the component
display area.

3.fill: fill is useful to resize the component according to the space available in the display area.

4. ipadx and ipady: are useful to leave space horizontally and vertically
Model-View-Controller (MVC) architecture
The Model-View-Controller (MVC) is a design pattern in web application development. It is a
way to organize our code. The application logic is separated from the user interface while
designing the software using model designs.
Swing uses the Model-view-Controller architecture (MVC) as the fundamental design behind
each of its components.
MVC represents the separation of the model of an object from its view and how it is controlled.
The MVC pattern architecture consists of three layers:
Model: The Model represents the data of the component.
View: The look (the visual appearance) of the component.
Controller: The Controller takes the input from the user on the view and reflects the changes in
the Component’s data. It acts as an interface between the model and view.
The controller determines how the component reacts to the user.
MVC Architecture:
Advantages of MVC Architecture
•The components are easy to maintain because there is less dependency.
•A model can be reused by multiple views that provides reusability of code.
•The developers can work with the three layers (Model, View, and Controller)
simultaneously.
•Using MVC, the application becomes more understandable.
•Using MVC, each layer is maintained separately therefore we do not require
to deal with massive code.
•The extending and testing of application is easier.
EventDelegationModel
• The modern approach to handling events is based on the Event Delegation Model, which
defines standard and consistent mechanisms to generate and process events.
• when an event is generated by the user on the component,the event is not handled by the
component.
• The Component sends (delegates) that event to the listener attached to it.The Listener will
not handle the event.It hands over (delegates) the event to an appropriate method.
• Finally the method is executed and the event is handled.This is called event delegation
model.
There are three participants in event delegation model in Java,
Events: Event is an object that is generated when end user interacts with components,such as
clicking a button, entering a character on the keyboard and Mouse click etc.
Ex: ActionEvent ,MouseEvent
Events Sources:Event source is an object that generates an event.
Ex: JButton creates an Action Event

Events Listeners:A listener is an object that listens to an event. A listener gets notified when an
event occurs.

The events which are generated from the source are handled by the
listeners. Each and every listener represents interfaces that are responsible
for handling events.

Ex: ActionListener. MouseListener, KeyListener


Advantage:
1.The advantage of Event Delegation model is the component is separated from the action
part.
For ex: We can create the component in java and action logic can be developed in visual
Basic
2.we can modify the code for creating the component without modifying the code for action
part
What is 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 follows the Delegation Event model.

What is Event

Event: Changing the state of an object is known as an event. When you click
on the Button the state change from uncliked to click.

Event is an action that is generated when user interacts with components, such as clicking a
button,pressing the keys on keyboard , Mouse click and selecting an item from the list, etc.

 The java.awt.event package provides many event classes and Listener interfaces for event
handling.
We can classify the events in the following two categories:
1.Foreground Events
Foreground events are those events that require user interaction to generate. In order to
generate these foreground events, the user interacts with components in GUI. When a user
clicks on a button, moves the cursor, an event will be fired.
2. Background Events
Background events don't require any user interaction. These events automatically generate in
the background. OS failure, OS interrupts, operation completion, etc., are examples of
background events.
Event Sources
What is Event Source?
• A source is an object that generates an event. There are various sources like
buttons, checkboxes, list, menu-item, scrollbar, etc to generate events.
• A Source should provide event information to Listener.
• A source must register to a listener to receive notifications for a specific event. Each event
contains its registration method.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
public void addTypeListener (TypeListener e1)
Type is the name of the event, and e1 is a reference to the event listener.
For ActionEvent we use addActionListener() to register.
Ex: public void addActionListener(ActionListener e1)
•Checkbox
• public void addItemListener(ItemListener a){}
•List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}
•Button
• public void addActionListener(ActionListener a){}
•MenuItem
• public void addActionListener(ActionListener a){}
•TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
•TextArea
• public void addTextListener(TextListener a){}
Event Classes:
Event classes are the classes that represent events
Event Object: At the root of the Java event class hierarchy is EventObject, which is in java.util. It
is the superclass of all events.
Methods:
1.Object getSource()
The object on which the Event initially occurred.
2.String toString()
returns a String representation of this EventObject.
1. Action Event: The ActionEvent is generated when the button is clicked or the item of a list is
double-clicked or a menu item is selected.
Ex: Button click,
The ActionListener interface is used for receiving the action events.

Methods:
1. getActionCommand()
returns the command string associated with this action.
2.getModifiers()
method returns a value that indicates which modifier keys were pressed when the event was
generated.
2.MouseEvent: MouseEvent is generated when a source such a mouse is moved,
dragged,clicked,pressed or released
Mouse Events are:Mouse_Clicked,Mouse_Dragged,Mouse_Pressed,Mouse_Released
Mouse_Entered,Mouse_Exited etc
Methods

1 int getButton()
This method returns a value representing a mouse button.when it is clicked it returns 1
if left button is clicked ,2 if middle button is clicked, and 3 if right button is clicked.
2.int getClickCount()
Returns the number of mouse clicks associated with this event.
3.The getX() and getY()
methods returns the x and y coordinates of the mouse within the component when the event
occurred.
3.ItemEvent: ItemEvent is generated when a source check-box or list item is clicked
There are two types of item events which are identified by two integer constants:
DESELECTED
The user deselected an item.
SELECTED
The user selected an item.
Methods:
1. The getItem() method returns a reference to the item that generated
an event.
2. The getItemSelectable() method returns a reference to the
ItemSelectable object that generated an event.
3.The getStateChange() method returns the state change(i.e, SELECTED
or DESELECTED) for an event:
4:KeyEvent: KeyEvent is generated when a source such as a key on the keyboard is
pressed,typed
These key events are following
•KEY_PRESSED
•KEY_RELASED
•KEY_TYPED
Methods:
1. getKeyChar()
returns the character associated with the key in this event.
2. getKeyCode()
returns the integer keyCode associated with the key in this event.
3. getKeyLocation()
returns the location of the key that originated this key event.
5:WindowEvent: Window Event generated when a source such as window is activated,
deactivated, opened or closed
Window Events:
WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_ DEACTIVATED, WINDOW_DEICONIFIED,
WINDOW_ICONIFIED, WINDOW_OPENED
Methods:
1. getNewState()
For WINDOW_STATE_CHANGED events returns the new state of the window.
2: getOldState()
For WINDOW_STATE_CHANGED events returns the previous state of the window.
3. getWindow()
method returns the object that generated the event.
6.ContainerEvent: Container Event generated when the component is added or removed from
the container
Methods:
1. getContainer() method returns a reference to the container that generated the event.

7.FocusEvent: Focus Event generated when component gains or loses keyboard focus
FocusEvents are identified by integer constants FOCUS_GAINED and FOCUS_LOST.

8. TextEvent: TextEvent generated when the value of TextArea or TextField changed.


TextEvents are defines the integer constant TEXT_VALUE_CHANGED
Event listener interfaces
The Event listener represent the interfaces responsible to handle events.

All listeners are interfaces from java.awt.event package.

1. ActionListener Interface: The ActionListener is notified whenever you click on the button or
menu item. It is notified against ActionEvent. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
Ex: public void actionPerformed(ActionEvent e)
{
//Write the code here
}
2.MouseListener Interface
MouseListener is notified when mouse is clicked ,pressed,entered and released. It is notified
against MouseEvents.
Mouse Events: mouse clicked ,mouse pressed,mouse entered ,mouse exited,and mouse
released.
Methods:
1.public abstract void mouseClicked(MouseEvent e);
Invoked when the mouse button has been clicked on a component.
2.public abstract void mouseEntered(MouseEvent e);
Invoked when the mouse enters a component.
3.public abstract void mouseExited(MouseEvent e);
Invoked when the mouse exits a component.
4.public abstract void mousePressed(MouseEvent e);
Invoked when a mouse button has been pressed on a component.
5.public abstract void mouseReleased(MouseEvent e);
3.WindowListener:WindowListener is notified whenever you change the state of window.

For ex:when you closed the window or opened the window

WindowListener methods:.
1.public abstract void windowActivated(WindowEvent e);
Invoked when the Window is set to be the active Window.
2. public abstract void windowClosed(WindowEvent e);
Invoked when the user attempts to close the window.
3. public abstract void windowDeactivated(WindowEvent e);
Invoked when a Window is no longer the active Window.

4. public abstract void windowDeiconified(WindowEvent e);

Invoked when a window is changed from a minimized to a normal state.


5. public abstract void windowIconified(WindowEvent e)

Invoked when a window is changed from a normal to a minimized

6. public abstract void windowOpened(WindowEvent e)

Invoked the first time a window is made visible.


4. ItemListener
ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent.
The It has only one method: itemStateChanged().
itemStateChanged() :The itemStateChanged() method is invoked automatically whenever you
click or unclick on the registered checkbox component.
Ex:public abstract void itemStateChanged(ItemEvent e)
5. KeyListener
The KeyListener is notified whenever you change the state of key. It is notified against KeyEvent.
Ex :when you type any character from the keyboard
It has three methods.
1.public abstract void keyPressed(KeyEvent e)
Invoked when a key on the keyboard is pressed
2.public abstract void keyReleased(KeyEvent e)
Invoked when a key on the keyboard is released
3.public abstract void keyTyped(KeyEvent e)
6.MouseMotionListener Interface
The MouseMotionListener is notified whenever you move or drag mouse. It is notified against
MouseEvent.
The MouseMotionListener interface is found in java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
1.public abstract void mouseDragged(MouseEvent e)
Invoked when you dragged the Mouse
2.public abstract void mouseMoved(MouseEvent e)
Invoked when you moved the Mouse
7.FocusLister Interface:The FocusListener is used for receiving keyboard focus events.
Methods:
1.void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.
Handling Keyboard events with an Example
• Keyboard events in java are generated when a key is pressed, the key is typed and a key is
released.
• The key Listener interface is handling keyboard events.
Each of the key Event handling methods takes a keyEvent object is its arguments.
• A KeyEvent object contains information about the key event.
The various methods available in the keyListener interface are as follows:
void keyPressed(keyEvent e)
The keyPressed ()method is used to call when a key is pressed.
void keyTyped(keyEvent e)
The keyTyped ()method is used to call when a key is typed.
void KeyReleased(keyEvent e)
The keyReleased()method is used to call when a key on the keyboard is released
void getKeyChar(): This method returns the key name related to the key pressed or released
int getKeyCode():This method returns an integer number which is the value of the key pressed
by the user.
Example To illustrate Key board Events
The following are the key codes for the keys on the keyboard.

To represent keys from a to z : VK_A to VK_Z

To represent keys from 1 to 9 : VK_0 to VK_9

To represent keys from F1 to F12 : VK_F1 to VK_F12

To represent keys alter key : VK_ALT

To represent keys shift key : VK_SHIFT

To represent keys control key : VK_CONTROL


Adapter Class:
Def:Adapter class is an implementation class of listener interface which contains all methods
implemented with empty body.
If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Adapter Classes are useful when we want to process a few of the events that are handled by a
particular event listener interface.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
To avoid this unnecessary code adapter classes are used for various listener interfaces
The Following are the Adapter classes
1.WindowAdapter :
The class WindowAdapter is an abstract (adapter) class for receiving window events .
All methods of this class are empty
2.MouseAdapter :
The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods
of this class are empty
3.KeyAdapter:
The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of
this class are empty
4.MouseMotionAdapter:
An abstract adapter class for receiving mouse motion events.All methods of these class are
empty
5.FocusAdapter:
The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All
methods of this class are empty.
6.MouseInputAdapter
The adapter which receives mouse events and mouse motion events. The methods in this class
are empty.
This class is present in javax.swing package
Handling mouse Events
MouseEvent: The user may click, press ,drag and move a mouse while interacting with the
application.
The Mouse Events are Cliked, Dragged, Moved, Pressed and Exited etc .
To handle the Mouse Events MouseLisener and MouseMotionListener interfaces of
java.event.awt package are used.
MouseListener
MouseListener is notified when mouse is clicked , pressed, entered and released. It is notified
against MouseEvents.
The MouseListener Interface has following methods.
1.void mouseClicked(MouseEvent e);
Invoked when the mouse button has been clicked on a component.
2. void mouseEntered(MouseEvent e);
Invoked when the mouse enters a component.
3. void mouseExited(MouseEvent e);
Invoked when the mouse exits a component.
4. void mousePressed(MouseEvent e);
Invoked when a mouse button has been pressed on a component.
5. void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
The MouseMotionListener
The MouseMotionListener is notified whenever you move or drag mouse.
Methods
1.void mouseDragged(MouseEvent e)
Invoked when you dragged the Mouse
2.void mouseMoved(MouseEvent e)
Invoked when you moved the Mouse
Mouse Event class has methods:
1 int getButton() : returns a value representing a mouse button.when it is clicked it
returns 1 if left button is clicked ,2 if middle button is clicked, and 3 if right button is
clicked.
2.int getClickCount(): returns the number of mouse clicks associated with this event.
3.The getX() and getY(): returns the x and y coordinates of the mouse within the
component when the event occurred.
Inner classes
Inner Class:The class defined inside another class or interface is called inner class.
In Java, an inner class is also known as nested class
 We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.It increases encapsulation.
 It can access all the members (data members and methods) of outer class including private.
 It requires less code to write.
 It helps in Code Optimization.
 Inner class is safety mechanism since it is hidden from its outer classes
Syntax:
class OuterClass
{
//code
class InnerClass
{
//code
}
}
Types of Nested classes
There are two types of nested classes
1 non-static nested classes (The non-static nested classes are also known as inner classes.)
2.static nested classes.
Non-static nested class (inner class)
i.Member inner class
ii.Anonymous inner class
iii. Local inner class
2.Static nested class
i.Member inner class:
A class that is created inside a class but outside a method is called member
inner class. It is also known as a regular inner class. It can be declared
with access modifiers like public, default, private, and protected.Syntax:
class OuterClass

Outer class code;

class InnerClass

Inner class code;

}
ii. Local inner class
A class defined inside a method is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block
If you want to invoke the methods of local inner class, you must instantiate this class inside the
method.
Rules:
 Local Inner class cannot be accessed from outside method
 We cannot create object of local inner class inside the main of the outerclass.
 We should create object inside the function in which it is defined to invoke the
methods of local inner class
 we can’t use private, public, or protected access modifiers with it. The only allowed modifiers
are abstract or final.
Syntax:
class outer
{
void method()
{
class inner
{
code;
}
} // method
} // outer
iii.Anonymous inner class
Anonymous inner class is an inner class with out a name and for which only a single object is
created. It should be used if you have to override a method of class or
interface.

 An Anonymous inner class can declare by the use of a new keyword.


 The Anonymous inner class is used when you want to use any class only once.
 Anonymous Inner classes are very useful in writing implementation classes for Listener
interfaces in GUI Programming.
 it is not possible to define a constructor for an anonymous class. Its name is decided by the
java compiler.
 Anonymous inner class can be created by two ways:
1.class (may be abstract or concrete).
2.Interface
syntax: Anonymous Inner class
where the class can be an abstract class or a concrete class or interface.
class t = new class()
{
public void method()
{
Code;
}
};
In the case of the anonymous inner class, a curly brace is followed by the semicolon.
we are declaring the anonymous class as well as creating an object of anonymous class. An
anonymous class can be providing body to interface, abstract/concrete class.
Create an anonymous class by use of abstract class
If you are want to create an object of an abstract class. You can use an anonymous inner class. In
the anonymous inner class, you must have to define the body of the method while creating the
object of that class.
2. Create an anonymous inner class by use of Interface
You can create an anonymous inner class by use of Interface. If you want to create an object of
an Interface. You can use an anonymous inner class. In the anonymous class, you must have to
define the body of the method while creating the object of that Interface.
Ex: write a java program to close a Frame using anonymous inner class
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String args[])
{
MyFrame f=new MyFrame();
f.setTitle("Anonymous Inner class");
f.setSize(300,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
2.Static Inner class
A static class created inside a class is called static inner class.We use the keyword static to make
our inner class static.
• It can be accessed by outer class name.
• Static inner class can have static members as well as non static members
• Static inner class can access static data members of outer class including private.
• Static innerclass cannot access non-static data members or non static method.
Syntax:
class outer
{
code;
static class Inner
{
code;
} }
Applet
• An applet is a special java program that can be embedded in the web page to
generate dynamic content . It runs inside the web browser and works at client side.
• An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
• Applets are used to make the website more dynamic and
entertaining.
• To create an applet, a class must class extends java.applet.Applet class.
• An applet can perform many functions such as graphics, play sound, animation,
arithmetic operations, play games etc.
For ex: A student can type his roll no in a text field and click the retrieve button to get back
his results from university server
Applets are useful to provide such interaction with the user at runtime
Applet=java byte code+html page
Note:
In general, execution of an applet does not begin at main() method.
 Every Applet application must import two packages - java.awt and java.applet.
 java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a window-
based, graphical user interface.

 java.applet.* imports the applet package, which contains the class Applet. Every applet that
you create must be a subclass of Applet class.
Advantages

 They are very secure.


 It works at client side so less response time.
 Applets can be executed by browsers running under different platforms.

Uses of APPLET or Applications


 Applets are used for creating animation and games where the images can be displayed.
 Applets are used for creating dynamic web pages
 It is useful to play audio or music in Applets
 Displaying documents
Disadvantage
 One disadvantage of Applets is that plugins are required at the client browser for executing
applets.
We can design our own applet program by extending applet class in the user defined
Syntax:
class className extends Applet
{
......
// override lifecycle methods
......
}
Explain the Life cycle of applet?
1.public void init(): is used to initialized the Applet. It is invoked only once.
ForEx:We can initialize variables,creating components in this method.
2.public void start(): This method is called after the init() method ,if the user maximizes the
web page. It is used to start the Applet.
ForEx:Any calculations or processing of data should be done and results also displayed
3.public void stop(): This method is called when Applet is to be stopped .If the user minimizes
the webpage.

4.public void destroy(): This method is called when the applet is being terminated from
memory.This method always be called before stop()
EX:The code related to releasing the Memory allocated to applet.
There are two standard ways in which you can run an applet :

1.Using a Java-Enabled Web Browser (By html file.)

Applets are executed by a program called applet engine which is similar to virtual machine
that exists inside the web browser at client side.

 If you are trying to execute your Applet in web browser


 first you need to compile your Java Applet program.
 create a separate HTML file and add the applet code in the html file by using <applet > tag
Syntax:
<applet code="name of applet class file" width="300" height="300">

</applet>

 Now you can click the HTML file to launch the applet in the browser.
Ex:
Step1 : create the applet program with name First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString(“Hello World",150,150);
}
}
Step2: compile the java applet
javac First.java
Step3: create an html file and place the applet code in html file
First.html
<html>
<apple code="First.class" width=200 height=200>
</applet>
</html>
Step4:
Open the html file in browser you will get the output
2.Using appletViewer
 Applet are executed by appletViewer Standard tool. An appletViewer executes your applet in
a window.

 This is the easiest way to run an applet


 To execute HelloWorld Applet with an appletViewer tool, you may also execute the HTML file
 HTML file is saved with
 RunHelloWorld.html

First compile the Applet


D:/kiran>javac HelloWorldApplet.java

Run the Applet

D:/ kiran>appletViewer RunHelloWorld.html

You get following output:


First applet program displaying msg (Executing applet through appletviewer tool)

Step1. Create java applet program

MyApplet.java

import java.applet.applet;

import java.awt.*;

public class MyApplet extends Applet

public void paint(Graphics g){

g.drawString("welcome II CSE-D",150,150);

} }
Step2: compile the MyApplet

D:/kiran> javac MyApplet.java

Step3: create a html file with name myapplet.html and embedded java applet in html program

myapplet.html

<html>

<applet code" MyApplet.class" height=200 width=200 ></applet>

</html>

step4: run the applet through appletViewer tool

D:\kiran> appletViewer myapplet.html

step5: you get output


Passing Parameters to Applet
• Parameters specify extra information that can be passed to an applet from the HTML page.
• Parameters are specified using the HTML’s param tag.
• We can get any information from the HTML file as a parameter to the Applet Program.
• The <param> tag is a sub tag of the <applet> tag.
• The <param> tag contains two attributes: name and value which are used to specify the
name of the parameter and the value of the parameter respectively
Syntax:
<param name="parameter name" value="value of parameter">
Ex:<param name=“emp" value="kiran">
To retrieve a parameter's value, we need to use the getParameter() method of Applet class.
syntax:
String getParameter(param-name)
String name=getParameter(emp);
Ex To illustrate ParameterPassing to Applet
Step1 :create a Applet
import java.awt.*;
import java.applet.*;
public class ParamAppletEx extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("name");
g.drawString("Name is:"+str,20,40);
}
}
Step2: compile the Applet
D:\applet>javac ParamAppletEx.java
Step3 :create a separate html file and embedded java code inside html
param.html
<html>
<applet code="ParamAppletEx.class" width="200" height="200">
<param name="name" value="welcome to java">
</applet>
</html>
Step4: run the applet

D:\applet>appletViewer param.html
Step5 you will get the output:
•Creating a swing Applet
• We can create swing applet by extending JApplet class of swing package.
• It provides all the functionalities of the AWT applet as well as support for menubars
and layering of components.
• We have to import javax.swing package and import java.awt package
• JApplet that can have all the controls of swing. The JApplet class extends the Applet
class.
• Swing applets provides an easier to use user interface than AWT applets.
Syntax
class className extends JApplet
{
......
// override lifecycle methods
......
}
Note:
When we create an AWT applet, we implement the paint(Graphics g) method to draw in it but
when we create a Swing applet, we implement paintComponent(Graphics g) method to draw
Compile: D:/kiran>javac SwingApplet .java
D:/kiran>appletViewer swingapplet.html
Painting in Swing
Swing's approach to painting is built on the original AWT-based mechanism.
The class Component defines a method called paint() that is used to draw output directly to the
surface of a component.
When drawing on Swing component, an application will override paint().
Because JComponent inherits Component, all Swing's lightweight components inherit the paint()
method.
Swing's painting involves three distinct methods: paintComponent(), paintBorder(), and
paintChildren().
paintComponent() This is the method that paints the interior of the component.
paintBorder(): Paints the border for the specified component with the specified position and size.
paintChildren()Tells any components contained by this component to paint themselves.
When drawing to the surface of a component, you must be careful to restrict
your output to the area that is inside the border.
To obtain the border width, we use getInsets(), shown here:
Insets getInsets():This method is defined by Container and overridden
by JComponent.
It returns an Insets object that contains the dimensions of the border.
The inset values can be obtained by using these fields:
int top;
int bottom;
int left;
int right;
You can obtain the width and height of the component by calling getWidth() and getHeight() on
the component.
They are shown here:
int getWidth()
int getHeight()
Ex to illustrate Painting in Swing
SWING COMPONENTS
Exploring Swing Controls- JLabel and Image Icon, JText Field,JPasswordField
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed
Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
Exploring Swing Controls- JLabel and Image Icon, JText Field, JPasswordField
All the swing Controls are present in javax.swing package
1.JLabel:
JLabel class is a component for placing text in a container. It is used to display
a single line of read-only text.
A JLabel can display either text, an image, or both.
creating the JLabel or Constructors
Syntax:-
1.JLabel l=new JLabel();
This constructor is used to create an object of Jlabel with no image and an empty string value.
2.Jlabel l=new Jlabel(icon);
This constructor is used to create an object of Jlabel with an Image icon.
3. Jlabel jlb=new Jlabel(“Hello”);
This constructor is used to create an object of JLabel with specific text.
These are the commonly used methods of JLabel class.
1. getText() : This method is used to return the String of JLabel.
2.setText(String text): This method is used to set Text to the JLabel.
3. setIcon(Icon icon): This method is used to set the icon on the JLabel.
4.setBounds(int x,int y,int h,int w): This method is to set the position and size of the component
manually.
5.setFont(Font F): This method is used to set the Font of the JLabel.

6.setForeground(Color c): This method is set the Foreground Color of text on the JLabel.

Ex: How to set Font

JLabel l=new JLabel(“Click Me”);

l.setFont(new Font("Verdana", Font.PLAIN, 18));


2.JTextField: JTextField is a class where the user can type single line of text. It is most widely
used text component.

Creating a JTextField object or Constructors

1.JTextField textField = new JTextField();

Creates a new TextField

2.JTextField jf=new JTextField(int columns);

Creates a new empty TextField with the specified number of columns.

4.JTextField textField = new JTextField(String text);

Creates a new TextField initialized with the specified text.

Ex: JTextField textField = new JTextField(“Enter the username”);


JTextField methods

1. setColumns(int n) :set the number of columns of the text field.


2. setText():set some text to the textField
3. setFont(Font f) : set the font of text displayed in text field.
4. int getColumns() :get the number of columns in the textfield.

5.addActionListener(ActionListener al): This method is used to adds the specific action listener
to receive action events from Text Field.
Ex to illustrate TextField and JLabel
import javax.swing.*;
class TextFieldEx
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField");
JLabel lb = new JLabel(" Enter Your Name : ");
JTextField t1=new JTextField(20);
t1.setBounds(100,155, 150,30);
f.add(t1);
f.add(lb);
f.setSize(400,400);
f.setVisible(true);
}
3.ImageIcon
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
To display images we have to use ImageIcon class.
syntax:
ImageIcon Icon = new ImageIcon(“C:\nature.jpg")
Image Icon methods
1. getImage() :Returns this icon's Image
2. getDescription():Gets the description of the image.
3. getIconHeight():Gets the height of the icon.
4. getIconWidth():Gets the width of the icon.
5. setImage(Image image):Sets the image displayed by this icon.
Ex to illustrate Image Icon
4.JPasswordField
• JPasswordField is a subclass of JTextField class. This JPasswordField class is used for inserting
passwords into the application.
• swing provides Jpasswordfield that takes user input in encrypted format.
Syntax:
JPasswordField pf=new JPasswordField();
It create a JPasswordField.
Method:
1.getPassword(): This method is used to return text of this component.
Swing Buttons
1.JButton: The JButton class can be used to perform some operations when the user clicks on it.
When the button is pushed, the application results in some action. It inherits the AbstractButton
class.
 And we can apply different swing features like setting colors,font for the button and tooltip text
Syntax:-
1.JButton jb=new JButton();
It is used to create a button with no text and icon.
2.JButton jb=new JButton(“OK”);
It is used to creates a button with text.
3.JButton jb=new JButton(Icon);
It is used to create a button with the specified icon object.
Syntax:-

ImageIcon icon=new ImageIcon(“nature.jpg”);

JButton jb=new JButton(icon);


JButton methods:
1. setText(String s):It is used to set specified text on button
2. getText():It is used to return the text of the button.
3. setEnabled(boolean b):It is used to enable or disable the button.
4. setIcon(Icon b):It is used to set the specified Icon on the button.
5. getIcon():It is used to get the Icon of the button.
6. addActionListener(ActionListener a):It is used to add the action listener to this object.
7. setFont():Set the Font style for the Button
Ex1 to illustrate JButton
import javax.swing.*;
public class JButtonEx
{
public static void main(String[] args)
{
JFrame f=new JFrame("JButton Ex");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setVisible(true);
}
}
Ex2: To illustrate JButton and JTextField when we click on JButton It should Display welcome
message on the JTextField
2.JToggleButton
JToggleButton class is used to create toggle button, it is two-states button to switch on or off.
 when the user clicks on the button it goes in to push state and some task can be performed.
 When the user clicks the same button one again ,it goes in to release state and another task
can be performed
 JRadioButton and JCheckBox are subclasses of the JToggleButton class.
Syntax to create JToggleButton
1.JToggleButton jt=new JToggleButton("label");
This creates a toggle button with a label on it
2.JToggleButton jt=new JToggleButton(label, ImageIcon obj);
This create a JToggleButton with label and image
JToggleButton method:
1.isSelected(): This method is useful to determine the state of the toggle button .
If this method returns true the button is selected,otherwise it is not selected.
3.JTabbedPane
• JTabbedPane class is useful to create a tabbed pane such that on each tab sheet a group of
components can be added. We can display tabs using a title, an icon, or both.
• A JTabbedPane component acts like a container for other Swing components, arranging them
in a tabbed pane.
• It inherits JComponent class.
• The user can choose any component from the tab sheet.

To create JTabbedPane
syntax:
JTabbedPane jtp=new JTabbedPane();
To add tab sheets to the JTabbedPane
Syntax:
jtp.addTab(“title”,object);
Ex 1 To illustrate TabbedPane
4.JComboBox:
JComboBox allows us to create a combobox,with a group of items which are displayed as
dropdownlist.The user can select single item only.
Combo Boxes require less space and hence very useful when size is small or limited.
1.JTo create JComboBox :Syntax
JComboBox jc=new JComboBox()
It creates empty combo box
2.JComboBox jc=new JComboBox(Object arr[])
It creates a new JComboBox that contains elements in the specified array arr[].
Commonly used Methods are :
1. addItem(object):Adds an item to the list
2. removeItem(object):Removes an item from the list
3. object getItemAt(int):Returns the list item at the index position specified by the integer argument
4. int getItemCount() :Returns the number of items in the list
5. int getSelectedIndex() :Returns the position of the currently selected item
6. object getSelectedItem() :Returns the currently selected item
Ex 1: To illustrate JComboBox to display countries
Ex 2 To illustrate JcomboBox
JCheckBox
The JCheckBox class is used to create a checkbox.
JCheckBox represents an item that can be selected or deselected, and which displays its state
to the user.
The user can select one or more options from a group of checkboxes.
Syntax to create JCheckBox class
1.JCheckBox jc=new JCheckBox ();
create a checkbox with out text .
2.JCheckBox jc=new JCheckBox (“apple”);
create a checkbox with text.
3.JCheckBox jc=new JCheckBox (“java”,true);
create a checkbox with text and specify whether or not it is initially selected.
4. JCheckBox jc=new JCheckBox("apple" ,ImageIcon i);
Creates an checkbox with an text and image.
Methods
1.setName(String text) : Sets a name on the JCheckBox, this name will not be displayed.
2.getName() : Gets a String message of JCheckBox, this name will not be displayed.
3.setIcon(Icon icon) : Sets an icon or image over the JCheckBox.
4.isSelected() : This method return true if the check box is selected otherwise it returns
false
5.getModel() : To know which check is selected by the user we should first go to the
model of the check box by calling getModel()
Ex1 to illustrate JCheckBox
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options.
It is used in filling forms, online objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We
use “ButtonGroup” class to create a ButtonGroup and add radio button in a group.
Syntax to create RadioButtons:
1.JRadioButton rb=new JRadioButton();
Creates an radio button with no text.
2.JRadioButton rb=new JRadioButton("Apple");
Creates an radio button with text.
3. JRadioButton rb=new JRadioButton(ImageIcon i);
create an radio button with an image
4. JRadioButton rb=new JRadioButton("Java",true)
create a radio button with text and specify whether or not it is initially selected.
Methods
1. isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will
return true otherwise false.
2. setText(String s) : It is used to set specified text on button.
3. getText() : It is used to return the text of the button.
4. setEnabled(boolean b) :It is used to enable or disable the button.
5. setIcon(Icon b) :It is used to set the specified Icon on the button.
JList class:
JList class is used to create a list which displays a list of items and allows us to select one or more
items. It inherits JComponent class.
To create JList syntax:
1.JList jl=new JList() ; create an empty list.
2.JList jl=new JList(object arr[]); creates an list with an elements of an array.
List class Methods:
1. getSelectedIndex()
returns the index of selected item of the list
2. getSelectedValue()
returns the selected value of the element of the list
3. getSelectedValuesList()
returns a list of all the selected items.
4. getSelectedIndices()
returns an array of all of the selected indices, in increasing order
JMenu:
JMenu class is used to create a menu with some options.After creating the menu,it should be
added to the menu bar
JMenuBar:The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.After creating the Menu,it should be added to the menu bar.
JMenuItem:
A menu consists of group of menu items. These menu items can be created using JMenuItem
class
To create Menu bar syntax:
1.JMenuBar mb=new JMenuBar();
creates the new MenuBar();
2.JMenu jm=new JMenu();
Creates a new Menu with no text.
3.JMenu jm=new Jmenu("File");
Creates a new Menu with a specified name.
Methods:
1.add(Component c) : Add component to the end of JMenu
2.add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu bar.
3.setJMenuBar():This method add menubar to the frame
Ex to illustrate Jmenu and design(Notepad)
JDialog:
The JDialog represents a top level window with a border and a title used to take some form of
input from the user. It inherits the Dialog class.
A JDialog is a top-level Swing container to host components and display a dialog.
it doesn't have maximize and minimize buttons.
Use of Java JDialog
In some applications, information just needs to be displayed with the “OK” button to use so as to
get confirmation from him before submitting the form
Syntax:
1.JDialog jd=new JDialog();
creates an empty dialog without any title or any specified owner
2.JDialog jd=new JDialog(Frame owner)
creates an empty dialog with a specified frame as its owner
3. JDialog jd= new JDialog(Frame owner, String title, boolean modal)
It is used to create a dialog with the specified title, owner Frame and modality.
Methods
1.CreateDialog(): This method creates a new Dialog box which contains JOptionPane.
2.showDialog(): This method is used to make dialog visible.
3.showOpenDialog(): We can use this method to open a dialog box with open on the approve
button.
4.showSaveDialog(): We can use this method to open a dialog box with save on the approve
button.
JScrollPane:
• A JSrollPane is used to make a scrollable view of a component.
• When screen size is limited, we use a scroll pane to display a large component or a
component whose size can change dynamically.
• scroll pane provides horizontal and vertical scroll bars automatically for scrolling the
components through the pane
methods:
1.setColumnHeaderView(Component): It sets the column header for the scroll pane.
2.setRowHeaderView(Component): It sets the row header for the scroll pane.
Syntax: JScrollPane jsp=new JScrollPane(Component , int ver, int hor)
Note:
Where component is the component to be added to the scroll pane
ver and hor specify the policies to display the vertical and horizontal scroll bar.
Some of the standard policies are:
HORIZONTAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_ALWAYS.

You might also like