0% found this document useful (0 votes)
2 views53 pages

Java Unit 5 Spectrum

The document discusses GUI programming in Java, specifically focusing on Swing, event handling, and applets. It outlines the differences between Swing and AWT, the limitations of AWT, and the Model View Controller (MVC) architecture. Additionally, it covers various components like buttons, checkboxes, and layout managers, as well as the characteristics and architecture of applets.

Uploaded by

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

Java Unit 5 Spectrum

The document discusses GUI programming in Java, specifically focusing on Swing, event handling, and applets. It outlines the differences between Swing and AWT, the limitations of AWT, and the Model View Controller (MVC) architecture. Additionally, it covers various components like buttons, checkboxes, and layout managers, as well as the characteristics and architecture of applets.

Uploaded by

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

UNIT GUI PROGRAMMING WITH

SWING, EVENT HANDLING


AND APPLETS

5
SIA GROUP

PART-A
SHORT QUESTIONS WITH SOLUTIONS

a1. What is Swing in Java? How it differs from Applet.


Nov./Doc.-18(R16), Q1())
(Model Paper-l, Q1(i)I
Answer
Swing
functionalities when compared to AWT
components.
Swing is a set of classes that provides more powerful
and flexible
as tabedpanes, scrollpanes,
Besides components such as buttons, check boxes and
labels. Swing adds other components such
image and a text
And each component in Swing have more capabilities. For example, a button can have an
trees and tables.
string with it.

Differences Between Swing and Applet


Applet
Swing
component. 1.It is considered as heavy weight component.
1. lt considered as light weight
is
It does not consists any type of rulees.
It posses look and
thread rules.
2.It consists of a fewfeel feature. This can be changed
.
2.
It does not posses such kind of feature or characteristic.
by UIManager. does not use model view control (MVC).
model view controller (MVC).
4. It
|lt makes use of - programn.
execute the 5. It requires HTML code to run the applet.
requires main method to
It Layout. 6. It uses AWT Layouts such as flow layout, Border layout,
.lt uses its own layout i.e., Box etc.
AWT?
a2. What are the limitations of
(April/May-18(R16), Q1(0)| Nov./Dec.-16(R13),
Q1(1))
Answer:
is a
GUI. There basic set of controls d:a1m.
Abstract Window Toolkit. It is a toolIKit to develop and
wnich is usaDic. AWI has the limited nature because d: nae
AWT stands for
graphical ineriace erent
windows defined in AWT that support limited
in it are translated inlo the equivalents that are plat form-specific such ne
VISual components that are present oaa
by the plaliorm. The AwI components are also called as heavy weioht
Component's look and feel is defined
make use of native code resources.
use of native peers are as follows,.
Problems faced because of the svstenme
'Write once and Run anywhere was threatened, because dillerent operating
1 Java's os
philosophy to different platforms.
and actions also varied on
other, the component's look
feel was defined by the platlorm which cannot be changed
easily.
2. The component's look and
used.
restrictions when heavy weight components were
3. There were disappointing
STUDENTS
JOURNAL FOR ENGINEERING SIA GROUP
ECTRUM ALLIN-ONE
5.2 TU-HYDERABAD
JAVA PROGRAMMING |JNTU-HYDER
Q3. Write tho difforencos botwoon swing and AWT.
Answer ModelPaperA,010

Swing AWT

1.Swing components are lightweight components, i. 1.AWT components iare neavy-weight components.
they are platform-independent. This means that AWI components arc platlorm-specif
The look and feel of cach component is delined by The look and fccl ol each component is determined by
swing. not by the platform. Hence, the working of tlhe platlorm.
swing conponents 1s consistent across any operatling
system or platform
Swing components are transpurent. AWT componcnts arc always reclangular and opaque.

Q4. Discuss about the MVC connection.


Answer: Nov /Dec.17(R13). 01p

A visual component has the following characteristics,


The ILOOK of the component when it is prescnted on the screen.

2. The RESPONSE Srom the component to the user.


3 The STATE INFORMATION related to the component.
Model View Controller or MVC architecture implicitly contains all the above characteristics. The design of MVC s bascd
on the characteristics of a component.
Model' term in the name of this architecturc coresponds to the state information related to the componcrnt
Example
When a checkbox is used, model holds a field that denotes whether or not the box is checked or unchecked.

View' term in the name of this architccture corresponds to lhow the component will look when it is presented on the scren
I includes determination of even those characteristics that arc affeciçd by model's current state.
Controller' the nane of this architecture corresponds to how the component responds to the user.
term in

a5. Discuss about FlowLoyout.


Answer ? O101
Nov./Doc.17(R13),
Flowlayout Mannger
Flowlayout Manager is the default layout manger. It is considercd to s out uhe
be simplest of all layout managers. ac
components Irom upper-lell corner Irom lclt to right and from top to bottom, by
When a line is filled it moves to the next row. The method it follows
separating the components witlh a s eic.
from left to right.
is similar to the wuy the words are wrappcu in
ao
Constructors
It has thrce types of constructors,
FlowLayout()
2 FlowLayout int how)
Flowlayout(int how, int hor, int ver)
06. Dofine ovont.
Answer
An cvent an action performed by the user. In the delegation status
is shows a
event model, an event is an object that sno
state changes in a source. Events are generaled when the uscr interacts with
the elements in a graphical user rlace.Som
m
dhe actions that generate events are pressing a button, cntering the data vin
keyboard, sclecting list,
intethe
an item in a chck
ete. These are all the cvents that are generated by a user by intcracting with a uscr
interfncc.

10LOok for tho SIA GROUP LOGO V on tho TITLE COVER boforo you buy
5.3
T-5 GUI Programming with Swing,
Event Handling and Applets
What are sources of events?
/Dec.-17(R13), a1(g)
uswer: Nov
The following are the sources of events,
Button
(ii) Checkbox
(ii) Choice
(iv) List
(v) Menultem
(vi) Scrollbar
(vii) Text components
(vii) Window.
Q8. What is event listener? Explain. Nov./Doc.-16(R13), Q1(0)
Answer:
Vith one o
A listener is an object which is notified when an event occurs. It must not only register
Dotifications but also must implement methods for receiving and processing
those notifications. The methods ior ee
processing events are defined in a set of interfaces found in java.awt.cvent.
Q9. What is an adapter class? Explain with an example. Nov/Doc.-17(R16), a10)
(Model Papor-l, Q10)|
Answer:
Adapter Class example, lo close
all the methods of
an interface to handle particular event.For
Adapter class is time consuming to override Window Listener interface. Eventhough we
necd to overTide
all the abstract methods of the
a window the user needs to override methods of this interiace.
only one method namely windowClosing( are forced to override all the remaining
we
we need not override all the
solution to this problem by providing adapter classes. By this adapter class ) an adapter
Java provides a
just override our interested method windowClosing( only by using
methods of WindowlListener interface, we can
class provided for WindowListener interface.
methods.
interface having more than one abstract
There is an adapter class for each
Eiample
WindowAdapter.
WindowListener has adapter class called
010. Discuss in brief about applets. Modol Papor-11, a10)
Answer: run wilh the help of Java enabled browsers such
program that is embedded in HiML document and
An applet is a Java runs in a Drowser. Unlike Java applications, applets don'
as, Internet Explorer. In other words, an applet is a Java progr
superclass "APplel.
at
An Applet class contains several
methods 1hosi
inherit the
have a main( ) method. All applets java.awt packages.
applet. All applets must import java. applel and
De execution of an
Q11. Describe applet architecture. Nov./Dec.17(R13), Q1(0)
Answer be different from console.hoeae
Since, an applet is a
window-based program, is
ecembles of nerup
intemupt
WIill
arcnitecture
Service
service routines.
roulines. An
An applet
applet waits
waits
for
for
an
an
ams
event to
architecture.
occur.
resembles set a set OI The AWT
Pplets are event driven. Ari applet calling an aner
evet which is provided by the applet should
uotifies the applet regarding an
event by ontrol to the AWT. In n siuations apple
where, an applel
situations where, requires to perform a repetitive
ake a suitable action and then
quickly retum contro1 ncW.
0
execution must be started.
thread of
On its own, an additional progra
interaction with an applet not the other way around. In a windowed not en the program needs
The userer initiates
calls some input metnods like readLine( ). But this is h applets, instead the
nput, it will prompt the user and then want and nowever he want. All these
interactions wi
the applet
user can interact with the whenever he
appiet esnond. Applcis can also conlain different
àiso contain like push
controls like ne buttons, check
should respond. Applets diflerent controls
boxes etc.. an
events to which the applet with these controls.
interacis
Sgenerated whenever user fnto two categories. They
into wo calcgon 1ney are applications and applets Applications
and appleis,
) method and r
Java programs can be divided contain main()
wnereas appicis does not contain main(
DEthod and runs with Java interpreter,
STUDENTS
SPEC JOURNAL FOR ENGINEERING SIA GROUP
EcTRUM ALL-IN-ONE
JAVA PROGHA nDERA
ERABAD
.4 Nov
12. State the differences between applets and applicauon
OR

How do applots differ from application program? Nov Dec-1bR1tt


nswer Applet
Application programs.
Applets are not stand-alonc
1Applications are stand-alone programs. ) method.
There is no main(
2. The main( ) method exists. lIke netseape for execution
3. They need a Java interpreter for execution They nced a browser
hard disk.
They can't access
4. They have no hard disk accessing restrictions.
securty for hard disk files
They need topmost
5 They docsn't need any security.

13. Why do applet classes need to be declared as public ApriluMay-18R16, 01


Answer n has the complete Java APl
browser. It an fully functional application since
ne applet will be run only on web is only if the applr
server when required. This is pOSible
onvenience. The applet attributes will be sometimes accessed by the
can be able to access i
declared as public. it is not declared as public no vendor
If
Q14. What are the differences botween JToggloButton and RadioBufton? Nov/Dec17(R16). 01
Answer
JToggleButton
it diflers. It has two states namely push and releze
JToggleButton looks similar to that of JButton but the functionality of
popping back. In order to release it in the user should
press it agin
When this button is pressed it remains as pressed rather than
between states for each button press.
lt gets released on the second push. That is toggles
it
derived fron
buttons are the objects of class JToggleButton. The classes such as JCheckBox and JRadioButton are
Toggle of selection s
when it is pressed. But it generates an item event when the concept
it. JToggleButton generates an action event In order tu
is pressed selection is performed and when it is pressed again deselection is performed.
used. When the toggle button
ltemListener must be implemented.
handle the item events, the interface called
JRadioButton states
JRadioButton class, which are similar to check boxes that is they also have two
Radio buttons are created using Selecting
are group of butons from which only one radio button can be selected at any time.
selected or deselected. Radio buttons is a subclass dt

radio button makes the previous selected radio button to be deselected automatically. JRadioButton class
other radio button iS made by adding the JRadioButton object to a ButtonGroup object
th
JToggleButton class. The grouping of the group.
1akes care of the state of the buttons in the
Q15. Write about checkbox.
Answer:
that provides the functionality of a checkbox. Checkboxes have two states
AJCheckBox is a swing GUl component
selected or not (true or false).
JCheckBox class which is subelass of JToggleButto JCheckBox
Checkboxes are created using of
JRadioButton is shown in the figure
below. 1ere
i u csmpie ol creating checkboxes and formatting the text as per the che
selected.
javax.swing.JComponent

javax.swing.AbstractButton

javax.swing.ToggleButton

iayax.swing.JcheckBox
javax.swing.JRadioButton
Eiaure: Hierarchy of JCheckBox
and JRadioButton

Look for the SIA GROUP


LOGO c on the TITLE
COVER before you buy
5.5
NIT-5 GUI Programming with Swing. Event Handling and Applets
U

PART-B
ESSAY QUESTIONS WITH SOLUTIONS

5.1 GUI PROGRAMMING WITH SWING

5.1.1 Introduction, LImitations of AWT

a16. What is swing? Discuss its features. List out the limitations of AwT.
Answer
Swin g ents.
compared to AW
classes that provides more powerful and flexible functionalities when tabbedpanes, scro
wng is a set ol such as
boxes and labels. Swing adds other components
Besides componenis Such as buttons, check
in Swing have more capabilities. For example, a button can have an image
and a text suE**
and tabies. And each Ccomponent
Features of Swing
The two basic features of swing are,
1. Light-weight components
2. Pluggable look and feel.
1. Swing's Light-weight Components components. These
componens ei
as light-weight to use, as they
The components of swing
are written in Java and are termed more flexible and elficient
are platform-specific. The
light-weight components are reclangies an
map to those peers that transparent, Eventually, shapes other than
directuy be
are rendered using the graphics
primitives, which will allow them to
also be drawn using the
light-weight components. into native peers. Thus,
all the
components as they cannot be translated
and feel of all the in a consistent manner.
Swing finds out the look working at all platforms and
components will be become capable of
Feel (PLAF) not the native peers.
Swing's Pluggable Look and code renders the swing component, but
feel of all its components,
as Java look-and-feel of a component
Swing controls the look and separated from its logic. The separated
component
look and feel of a
Thus, it is possible to keep the
advantages,
will provide the following changing the code of that component.
plugged into a component without these styles can
be
A new look-and-feel
can
together to correspond to different GUI styles. Any of
looks-and-feels can be grouped
a specilic style is plugged-in,
that style will be used to render each of
) In addition, several style. when
plugging into that
be used by simply
the components. platforms without any change..ots
defined that can be used in all types of
look-and-feel can also be a specific platform.
(l) A specific can also be designed that corresponds to
look-and-feel
(iv) Alternatively, a
basic set of controls, dialo
Limitations of AWT is a too T
develop GUL. There is a
looIkit. it has the limited nature because different
stands for Abstract Window limited graphical interlace whicn is usable. AWT platform-specific.
AWT AwT that support that are
are iransiated no ine equivalents
present in it WT components are also called as heavy weight components as they
components
visual components that are defined by the platlorm. Ihe AwT
Component's look and feel
is
resources.
make use of native
code
use of native
peers are as follows,
of the
Problems faced because anywhere' e'was
v threatened, because different operating systems varied from each
once and Run platforms.
Write on different
Java's philosophy to look and actions aiso varied oot
component's defined platform which cannot be changed easily.
other, the was by the
look and feel
Thehe component's
disappointing restrictuons
when heavy weight componeni ised. 3 e
There were
Example component is alwaysalways rectangular aand opaque respectively.d srtd
of a heavy weignt
The shape and colour ENdINEERING STUDENTS
JOURNAL FOR SIAGROUP
PECTRUM ALL-IN-ONE
5.6 JAVA PROGRAMMING IJNTU-H DERABAD

Q17. With a neat sketch, explain the Swing Architecture.


Answer NovDec.16R13
Swing Arehitecture
components compared to that ofAWT. They are event driven and nroi
vide a good
Swing components are enhanced prognr
concepts. They are light weight components which makes use of model-view
ming approach through 0OP controll architectur
All the components of swing are contained in
javax.swing package.
showm in figure below,
The hierarchy of swing components is
Component

Containcr

JComponent

JPanel JLabel JTextComponent AbstractButton

JTextFicldJTextArea JButton JMenultem


Figure: Swing Components Hierarchy
The hierarchy of swing components consists of following elements,
Component: It is a visual control which is independent.
(i) Container: It is a type of component that contains other components.
(ii) JComponent: It is a class that holds all the other components. It inherits
provides pluggable look and feel.
the AWT
classes container and components aN

(iv) JPanel: It is a light weight swing container. It


is a component that can be added to contentPane
of JFrame.
(v) JLabel: It is an easiest-to-use component that is used to
create a component.
(vi) JTextComponent: It is the base class
for JTextField and JTextArea.
(vii) JTextField: It allows the user to
enter or edit single line of text.
(vii) JTextArea: It allows the user to enter or
edit multiple line of text.
ix) AbstractButton: It is the base class of JButton
and JMenultem.
JButton: It is a push button associated with
icon, a string or both.
(xi) JMenultem: It represents an list of item
in the form of menu.

5.12 MVG Archtecture,


Componenta, Contalner
Q18. Discuss Model Vlew Controller (MvC) architecture.
Answer Q10
A visual component has the following characteristics, Model Papar4,

The LOOK of the component when it is presented


on the screen.
2. The RESPONSE from the component to the user.
3. The STATE INFORMATION related to the component.
Model View Controller or MVC architecture implicitly based
contains all the above s
on the characteristics of a component. characteristics. The design of M
Model' term in the name of this architecture cormesponds to the
state information
Example related to the component.
When a checkbox is used, model holds a field that denotes
whether or not the box is
checked or unchecked
Look for the SIA GROUP LOGO 2 on the TITLE COVER
before you buy
UNIT-5 GUI Programming 5.7
with Swing, Event Handiing and
Appios
VIcw lcrm in the name of this architecturc corrcsponds
to how the component will lo0. vi
ncjudcs delermination of cven those characteristics that are aflected by model's current
COnrollcr term in the name of this architecture corresponds to how the component respon
nc a each will not allect
Component is distinguishcd
into a model, vicw anda contröller, a change in implementation of
the other two.

SWIng makes use of a modificd version the view and the controller
of MVC. As its componcnts are not bencfitcd when
hatve a high level ol scparation between
them. The modificd version of MVC has a logical entity called
'UI delcgate whicn is a
"
combination of the view und controller.
Thus the architecture used by the swing is called a "Separable
Model Architecture or
a

Model-Delegate Architecture'. "


compone hus
'Asthe model-delegate architecture is used in Swing, fron the look and feel of the
it separates the model
a change in the look and feel of the
component will not affect the use of the component wilhin a pro
a nou
use of two objects in order to support the model-delegate archítccture. One to represent
esnake
and the other to represent a UI delegate. Interfuces
define the models. For instance, a button's model is defincd using
interface. Ul delegates are classes and they inherit Component Ur. For instance, the button's Ul delegate is 5uton
Q19. Describo about varlous components and JFC contalners in swing
OR
Discuss about components and containors. Nov/Doc.-17(R13), a10(a)

OR
What are the various compononts of Swing? Explain.
Refer Only Tople: Components of Swing)
Answer Nov./Dec.-17(R16), a11(b)

Components of Swing
Swing is a set of classes that provides more powerful and flexible functionalities when compared to AWT components.
Besides components such as buttons, check boxes and abels Swing adds other components such as tabedpanes, scrollpanes,
trees and tables. And each component in Swing have more capabilities. For example, a button can have an image and a text
string with it.

Unlike AWT components that are heavy weight, Swing components are light weight because they are writen entirely in
are platform independent and hence they have the same look and feel on different operating systems or for
Java and therefore
cach platform.

The classes that are used to create the GUl componcnls arc irom javax.swing package are ,
as follows.
Description
Class
JApplet This class is the Swing version ofApplet.
This is Swing version of Button class that generates
thec
JButton an event when button is
presed.
JChecklBox This class is the Swing Checkbox class.
1is the combination of a drop-down list and text ficld
JComboBox from which uscr can
an item by clicking in the text or by typing into select
the box.
JLabel This is the Swing's Label class that provides un area
for uneditable text.
This is Swing's RadioButton class.
JRadioButton
It provides d scrollable window,
JScrollPane
It provides a tabbed window.
JTabbedPane
This is Swing's Textl*icld class for user to input
JTextField data from keyboard.
It provides a trec-bascd control.
Tree
FOR ENGINEERING STUDENT
TRUM ALLAN-ONE JOURHAL -S'AGRUP
JAVA PROGRAMMING IJNTU-HYDERAD
RABADI
8
JComponent class is the superclass to most of GUI of window platform. Whenever user want to draw JE
a
mponents of Swing. It has the method that can be applied to request moves to the underlying operating system Fram
th for
ny subclass of JComponent. Swing components that subclass of the frame to be drawn that is why it is called heavv.
component. JButton, JSlider ete., are examples for iogh
Component have the following featuures,
Swing components. When a window is no longer igh
They provide a pluggable look and feel when the program an application, the window must be explicitly dispocej
executes on different platforms. can be achieved by calling windows disposc( ) method. This
I
Shortcut keys are provided tó access GUI components can display a message in the title bar of the frame. set:
Size().
directly through the use of keyboard. is used for dictating the size ol he frame. set Visible
0olean
val) decides whether the lrame to appear on the monitor
3. If several GUl components initiates the same action then If its value is true it appears else it won 't appear.
or not
common event handling capabilities are provided.
Program on JFrame
4. Tool tips are provided for GUI components when the
mouse cursor is positioncd over components for a short File Name: JFDemo.java
period of tim.
import javax.swing. *;
S. It provides support for assistive (related) technologies
such as Braille screen for blind readers.
import java.awt.";

6. It also provides the support for u public class JFDemo extends JFrame
interface localization
er
ie., customizing the user interface for display in different
languages and cultural conventions.
JButton rb, gb, bb;
JFC Containers
public JFDemo()
For answer refer Unit-V, Q20.
a20. What are various JFC containers?
List them
according to their functionality. Explain Containerc= getContentPane(O:
each
of them with examples.
C.setLayout(new FlowLayout( );
Answer rb new JButton("Red");.
There are two different types gb new JButton("Green");
defined in of containers that are
swing. They are, bb= new JButton("Blue");
. Top-level or heavy-weight
containers. C.add(rb);
2. Light-weight containers.
c.add(gb):
1. Top-level or lHeavy-weight
Containers C.add(bb);
The top level containers
JFrame, JDialog and JWindow. defined in swing are JApplet, setTitle("JFrame by SN Rao");
These containers inherit setSize(300,350);
classes ofAWT but they 'Component' and
do not inherit 'Container setVisible(true);
Jcomponent' class.
The top level container
containment hierarchy. Thus is always
any container at the lop of a
level container within it. A cannot public static void
conlainment hieTarchy have a top- main(String args[ )
with a top-level container. The always begins
top-level container, JFrame
mostly uscd for un application is
and JApplet is used
for applets. new JFDemo( ):
(a) JFrame
JFrame is a useful class for
creating a window.
is a window with a title bar JFrame
and a border.
JFrame class is
subclass ofjava.awt. Frame, this in
turn is a subclass ofjava.awm.a Output
Window. JFrame is one of
the important swing GUI
but not considered as a light weight components ane
GUl component. In by ARen
to many swing components, JFrane is contrast
not completely writjen
in Java. When a window is displayed
from a Java program,
the window style is copied irom the underlying
system, i.e. JFrame developed on Unix is different operating
from that

nefor the SIA GROUP LOGO


Y2 on tho TITLE COVER
bofore youbuy
NIT-5 GUI Programming with Swing, 5.9
Event Handling and Applets
JApplet
2 Light-weight Containers
JApplet class is the fundamental to
Swing. JApplet extends JPanel
Aplet. Applets which use Swing should be subclasses
of JApplet. that is defined
Anplet is rich with functionality
which is not found in Applet. JPanel is one of the light-weight containers 'JComponei!
JApplet supports dilleTent "passes", like in swing. The light-weight containers
inherit the
content pane, glass pane organizing and managing groups
and the root pane. when a component class and are generally used in
JApplet, we must not invoke the add( )
is added to an instance of
of components that are related to
cach other. This is possible
method of the applet. Instead light-weight container within it.
call add() for the content pane because a container can have a
of the JApplet object. The content
nane is obtained by using a method as follows: Program on JPanel
Container getContentPane() File Name: JPDemojava
A component can be added to a content pane by using import javax.swing.":
the add) method o1 the container as shown below. mport java.awt";
void add(comp) public class JPDemo extends JFrame
comp is nothing but the component which is to be added
to the content pane. JButton rb, gb, bb, mb;
Program on JApplet JPanel jp:
File Name: JADemo.java public JPDemo()
import javax.swing.";
Containerc = getContentPane():
import java.awt.";
c.setLayout(new FlowLayout( ):
public class JADemo extends JApplet
rb new JButton("Red"):
gb = new JButton("Green"):
JButton rb, gb; bb new JButton("Blue");
public void init() mb new JButton("Magenta");:
jp = new JPanel();
Container c = getContentPane( ); jp.add(rb):
C.setLayout(new FlowLayout( ) ip.add(gb);
rb = new JButton("Red"); jp.add(bb);
,
gb = new JButton("Green"); jp.add(mb):
c.add(rb); c.addop. "North");
c.add(gb); setTitle("JPanel by S N Rao");
setSize(300,350);
setVisible(true);
JApplet:
HTML file that executes above
File Name: JA.html public static void main(String args[ })
"JADemo.class" width="300"
applet code = height="350">
new JPDemo0;
lapplet
Output
Applet Viewer: JADemoclass Output
Applet
EWanel by SNRao
Red Green

ADplet staled.

FOR ENGINEERING STUDENTS SIA GROUP


EIRUM ALL-IN-ONE J0URNAL
SP
JAVA PROGRAMMING IJNTU-HYDERA.
BAD
5.10
JComponent with Imagelcon icl = new Imagelcon("Duke.
Q21. Explain the functionality of
lab2 new JLabel("How do you do"
example. Differentiate JComponent and JPanel. Icl,
SwingConstants.LEFT
Answer: lab2.setToolTipText("Well Wishes"):
JComponent c.add(lab2);
The JComponet class is the base for all swing
components used in a window as part of the GUI. Since this / using JLabel constructor with no argum
uments
/Properties are set later
class is derived from container, all of the swing components are
Imagelcon ic2 = new Imagelcon("javalor
alogo.gif
also containers. The subclasses of JComponent define a range
of standard components like menus, buttons, checkboxes etc. lab3 = new JLabel( :
lab3.setText("All are Okay"):
These classes are used for creating the GUI for our application
or applet. All the swing component classes re delined in the lab3.setToolTipText("Quite and Pencefur
javax.swing package and have class names which begin with J. lab3.setlcon(ic2);
Class JComponent is the superclass to most Swing lab3.setHorizontalTextPosition(SwingConstanis
components. This class defines the set of methods that can be CENTER)
applied to any subclass of JComponent. lab3.setVerticalTextPosition(SwingConstants
Swing components that subclass JComponent have many BOTTOM); 7 kept in
if
features includin; l comments, on and label come in one line
1

1. A pluggable look and feel that can be used to customize c.add(lab3);


the look and feel when the program execules on different / to close the window, the shortest way
platforms.
add WindowlListener( new WindowAdapter()
2. Shortcut keys for direct access to GUl components
through the use of keyboard.
public void windowClosing(WindowEvent e
3. Common event handling capabilities for cases where several
GUI components initiate the same actions in a program.
4. Brief descriptions of a GUI component's purpose (called System.exit(0);
tool tips) 1hat are displayed when the mouse cursor is
positioned over the component for a short time.
. Support for assistive (related) technologies such as Braille setTitle("Learning JLabel");
screen readers for blind people. to give title 1o the frame
6. Support for user interface localization, customizing the setSize(300,350); // 1ogive size to the frame; 300
user interface for display in different languages and pixcls width and 350 height
cultural conventions.
set Visible(true); // to make the frame visible
xample
land if false frame is not seen
JLabel is used to display some message to the user.
JLabel does not generate any events.
The label can be aligned public static void main(String args[ ]).
in different ways like left, right,
center etc.
importjavax.swing.";
import java.awt."; // for Container new JLabelDemo( ); /just call the construe
class
import java.awt.event."; // for
window closing
public class JLabelDemo'
extends JFrame Output
JLabel lab1,lab2,lab3; Leaining JLabel
public JLabelDemo()

Jlefto World
Containerc=getContentPane( How do you do?
c.setLayout(new FlowlLayout(
); Well Wishes|
1 layout managers discussed shortly
/ using JLabel constructor with a string
argument
labl new JLabel("Hello World"):
l creatinga JlLabel object JAVA
labl.setToolTipText("Greetings"); All are Ok
c.add(labl); / to add the label to the container
// using JLabel constructor with a string, icon
land alignment arguments This program uses methodot
JComponent class a )
setToolTipText( ponent
to give deseription JLabel co
for the SIA GROUP LOGO
2 on the TITLE
of
CoVER before you buy
GUI Programming with Swing, Event Handling and Applets 5.11
NT-5
Kwnpenent V's JPauel createlayout(l1, 12, 13, b);
Jomponent is a subelass of container class. It is setTitle("lcon Drag & Drop"):
SetDefaultCloseOperation(JFrame,EXIT_ON_CLOSE)
ot
* suervlass all the light eight swing components.
eneintoft is visihle by detult when first ereated. JPancl is setlocationRelative'To(null):
ulass JCompnent class. Iu is an area that can be used
a sot ot components. JPanel does not have a border. DrugMouseAdapter extends
MouseAdapter
gTP private class
Pcl can also be added to some other component like JFrame.
1YRYe Janel can be used as both a component as well as mousePressed(MouseEvent mc)
wvhen tirst created. The public void
1Ntainer. JN'anel is VIsible by detault
lavNut tor Jl'anel is Flowlayout. c.getSource( );
dut to movaldrag a component placed in Swing
JComponent jc = (JComponent)
je.getTransferHandler( );
Q22. How TransferHandler handler = TransferHandler.COPY):
Container? Explain. handler.exportAsDrag(ic, me,
Nov./Dec.-17(R16), Q10(b)
Ansuer : in
All the sing components in Java does not have built
and it needs to be createLayout(JComponent... arg)
dag supyrt. JLabel is one such conponent private void
The below program shows
andd support dras tiunetionality.
Am ivns can e movexd draggd.
Tvo labels and one button ar* getContentPane( );
Container pane =
plad in the swing container content
pane they are displayed
GroupLayout gl = new
GroupLayout(pane), u 49.A,

by default for the label. pane.setLayout(gl):


The drag support is not activated gl.setAutoCreateContainerGaps(true);
mouse adapter is registered for both
Rr this purpae a custom Transferl Handler class for the icon
gl.setAutoCreateGaps(true);
adek Every component has a and targets need the support of gl.setHorizontalGroup(gl.createParallelGroup
sources (GroupLayout.Alignment.Center)
merty. Both the dray
TransferHandler. .addGroup(gl.createSequentialGroup()
inmport javax.siwing.*: .addComponent(arg[0])
mport javax.awt.Container: addGap(30)
javar.awt.EventQueuc:
mport javax.awt.event.MouseAdapter .addComponent(arg[1])
mport javax.awt.event.MouscEvent; .addGap(30)
umport javax.awt.event.MouseListener addComponent(arg[2])D
import
extends JFrame
public class Move .addComponent(arg[3], GroupLayout.DEFAULT_SIZE,
GroupLayout. DEFAULT_SIZE, Integer.MAX_VALUE)
publicMove)
gl.set VerticalGroup(gl.createSequentialGroup()
initUI()* addGroup(gl.createParallelGroup()
addComponent(arg[0])
pivate void initUI( .addComponent(arg[1])D
Imagelcon(""e/sre/img-png"):
.addComponent(arg[2])
lmagelcon il = new Imagelcon("e/sre/p.png"):
addGap(30)
Imagelcon i2 new Imagelcon("c/sre/smile.png"):
.addComponent(argl3))
Imagelcon i3=ne JLabel.CENTER): d g
new JLabel(il, JLabel.CENTER):
Label I1- JLabel(i2, pack( );
JLabel 12 = new JLabel(i3, JLabel.CENTER); );
new DragMouseAdapter(
JLabel I3-
Alouselistener It- New public static void main(String[] args) 0gt ste
I1addMouseListener{lt);
2.addMouselistener(l): EventQueue.invokel.ater(()-> e
B.addMouselistener(l):
JButton(i2): Move ex = new Move(); 7Lg
Button b new TransferHandler("icon"): ex.setVisible(true); 3
bsetFocusable(false)
.setTransferHandlertnew landler("icon");
Tranusfer
landler(new TransferHandlert"içon"));
2setTransferl
BsetTransferlHandlertnew TransferHandlert"icon")):
TransferHandlertnew STUDENTS
bset ENGINEERING SIA GROUP
ETRUM
ALLAN-ONE JOURNAL
FOR 2
JAVA PROGNAMMING IJNTUHYDERABA
12 HAD
ie manager is u6eful place he seotlbars
5.1.3 Understanding Layout Managers, a
bden. 1 thedefutlt layul anager hlanne, Dialo
Flomayout, BorderLayout, GrldLayout, ile Diulo and
CsrdLsyout, Grdisgnyo Conatrue tor
Vihat is on Lsyout mansyer Éxplsin different Comotntor of he Jolerl.ayoul pianager aeas followa
3. types of Layout msnagsrs,
derlayou) oeales a delault layouu
Aprtloy 1810), 9110)
oiderl ayouint h0r, jil ver) cpealesa border layou
with a speujliud lnionlal and vejtical apace
OR ween
he ompmenls
List and sxploln d1f19rsnt iypes of Jayout oderuyot opecifhda following constants.
manag9rs ith sullabls sxsnples, Hodeay.NTR
tr
Des AH18), 019t) orderl ayutiANT
OR ordorl ayout. WINT
Explsin various layout managers In JAVA, ondevl nyouNORII
Bonderl ayou,8OUT
yy D1B19), 0110)
OR Vxmple
Erplsin stout GridBsyLoyout mporl joVX.wing."
nmpowt java awl.",
Onefer Only Tiple Gndbaylayom Manuge)
ublic cluns lorderDeo extends JPrame
Answer 4v JD 7(N13), 9s()
ayvat Msn»yr publio HorderDemo )

Lsytrut manager is esponsible sor Branging the


uynenta mutmatically witiin s window, It will be ussuxciated Contuiner gotontentpane),
wit every ondaines oject. A \»yut manayer
is an instaIKA O Borderlayout bl- new Horderl,ayoul( ),
chass thad implerrerts layout manayer inerlace, The below C.hetlLayout(bl),
frgae thrws the varins AWT l»yout mangers,
JIulton bi new JBulton("Nortl;
Jutton b2 new JBiutten("Soutl");
JIutton b) new JButton"las");
JButton b4- new JButton("Weal");
JI$utton bs new
Juton"Center"),
C,add(hI, b/NORTI);
C.ndd(h2, b/.SOUTI);
Figore Hiersrchy of L»yoyt Menage C.addch3, b/.iAST);
C.addba, bi.WEST);
A layrn nanayr cas be et
using e1layoutl ) method, c.nddbs, b/CINTER);
f is en 1, then delauh manayet is used.
The genersl fom selitle("Border Iayout Manager")
of slayonal ) nethvyd is shrun below,
sct8izt400, 200);
vrid vayralIayotiMsnager obj) setVisiblet(truc);
Here, 'h' indicates the otjoct
of the desircd layout setDefaulICloseOperation(Jl'une
EXIT_ON CLOSI,
(a) B derlayuut Msnagr
nderayout lrys nst the annpomets in fouir differem public stutic void main(String nrgsl )
regyma iz., iorth, Soruth, Vast ad West
and one at te enter.
new BorderDemo );
f it ill be upwA bry tie eneT 1egjene Ii can d
up t
unnnets, tme fn cwh regym. Te cnnpments of onth
vnah egom erend rivpntally. Ts cnnpmen snd Output
of ast an
Wet regymapard vertically and centet 1egomexpand urnud
l te renainity sp take 9rdeyoul ManaPI
in tho laynd,
If th n unuth sezirms is nwn encupied then
West,
cennet erd Vast rexjyms erpand vernically o
xupy te space. If
act on West ezm in rn ocupicd then center segin owcupies
he spac horiumntally If Center regim is left empty then
no
h GUi unnpnent twupies th opor arvd the s
is
eupy If ull the ezims ure filled then the comtajner apac is
len
e nbovo propom urentes tive biuttons'und
hem
fofl of GUI amynets
nto ove diflerent reglons,
PDTLOokfor the SiA GROUP LOG0 on the TITLIE CovEn bufora you buy
T-5 GUI Programming with Bwing, Event Handling and Appteta

Gridiayout Manuger (e) Plowl.ayout Managr manger, 15


Mannger is the default layout
GridLayout in used to lny lhe componentn in n two Owayut It lays ol h
layout nafiners,
LncOuhonal grid in the form of rows and columns. Hach idconsidered to be nimnplest of alI to ripht nd Tro
from upper-lel coner from leh
cell) contains onc Componen, Componcnts expand their nize onponcnts
top to bottom, by sepuruting method j
to
ilar that of Borderayoul cofnpoments. And every component
maves tn the next row The
sane widih and hcight. Wna ne iu illed it wrapped in a pngr
the the words are
Jollows in similnr to the wny
Constructorn
constructors, ie, Srom lefl to right
I dcfines thc):following Constructors
GridLayout( aliridlayout
Jt crcates with ninyle colunn. of consiyctor, components
has three types creates delault Jayout ic.,
GridLayout(int roWs, int columns); t creates Vowlayout( ): It
5 pixels apace
with
between cach
GridLayout wilh given rows and columns. are placed in centre
GridLayout(int rows, int colunns, int hor, int ver): I Component a layoul with
he
. PlowlLayout(int how): Il crestes These uliypments
creates a Gridlayout with the given rows, columns
und
the componcnts,
horizontal and vertical spaces. npecilicd nlignment of
Can be,
Example Plowlayout.JEFT
import jaVa.am."; Flowlayout.CENTER
import javax.nwing." Plowl.ayout.RIGIT
public class GridsDemo extends JFrame Plowlayonut.LEADING
Flowlayout. TRALING
It crecated a layout
public GridsDemol ) Flowlayout(int how, int hor, int ver): as well as the
alignment
manyer with the specificd the
spaces to be left between
horizontal and vertical
Container c ge1ContentPanc( ); Components.
4):
GridLayout g new Gridlayout(3,
Exumple
c.sctlayout(g); import javax.swing."
fortint i-0; i<12; it+) import java.am."
c.add(ncw JButton("Bulton" +i) import java.awl.event.";
setTitle("Grid Layout
Manager");
public class Flowlayout
cxtends JFramc implemnents
Actionl.istener
setSize(200, 200);9
setVisible(true);
setDefaultCloseOperation(JFrame. Flowlayout f fi
EXT_ON CLOSE, Container c;
JButton bl, b2, b3;
public Flowlayout(
D

main(String args[ )
public static void
f new Flowlayout(FlowLayout.LEFT);
);
new GridsDemo( c getContentPane(D
C.setlayout();
bl new JButton("Lefn Alignment");
b2-new JButton("Center Alignment");
Output
b3 new JButton("Right Alignment");
Grid1 ayout Managrer bladdActiornl.istener(this);
Buions b2.addActionlListener(this);
Button2
bunond Buton1 b3.addActionlistener(this);
C.add(b);

Buon6
Buton7 te fuf,C.add{b2);
C.add(b3)
Budons
setTitle("Flow Layout Manager")
setSize(500, 300);
Button11
udor
uton 10 setVisible(true);

STUDENTS3
JoURMAL FOR
EMdiNEERIMG SIA GROUP
TRUM ALANONe
JAVA PRoGRAMMING (JNTU-HYDERABAn
B.14
actionl'orlibmed(Aotionllvont o) Containere
publio vold
publicCardl.ayoutDemo()
bdn (J1uttm) o getßouree( );
Jutton
CgetContentPanc()
if(btn- b)
,actAlignent(Vlowl,ayout,1.rT); String hotcla| "Tajmahal", "Tnj Banjar
"Central Court", "Viceroy")
olao (btnb2)
if.netAlHgnmont(llowl.ayout.CENTER); Siring buildings| |=("Chiran Palace", "Valaknm
Palncc", "Charninar", "Gülconda Fort")
olne if(n-- b) String parka[ ] = P°lumbini park", "Z00 Dak
I.nctAlignmon(lowl.ayout.RIMUT);
.layoutCotainer(o); "Indira park", "Sanjivu park"|;
String visitn ] "Ramoji Pilmciy-
})
"Planetorium", "li-Tcch city" "Shilparaman
publio atatle vold maln(String args|
hlnewJI.ist(hotels);
new l'lowlayout( ):
pl new JI.ist(park»):
bl new JIList(buildings);
vl new J1.ist(visits);
cl new CurdIuyout;
Tho hove progrnm inltially Hcls the flow lnyout as
layout manager with the componcta laid an I.:T. pl new JPancl( );
When tho user prennen a button uch as "CENTER" pl.hctlLayout(cl);
button, then the flow layomt la pet an in CENTER. pl.add(hl,"");
(d) Cardl.ayout Manager pl.add(pl, "p");
Cordlayout Munager la dilerent from all otier luyout pl.ndd(bl, "b");
manngera, lU ntrangen the componcntn in tho form of deck of
pl.ndd(vl, "");
Carda, wliero only thhe top mont in vinible. We can plnce ony card
from deck at the top using following methods. b new JButton("First Button")
vold Irnt(Container deck) lb new JButton("Last Bulton");
vold lust(Container deck) nb new JButton("Next Button'");
vold nexi(Container deck) pb new JButton("Previous Button'");
vold previous(Container deck) p2 new JPanel( ):
vold show(Container deck, String cardName) p2.sclLayout(new GridLayout(1, 4)%
As their nnne lmplien, they nre uNcd to accenN the firnt, p2.add(b);
last, next or previoun curd. The nlow) method uke out the e
exuct card Irom the deck using itn nome.
p2.dd(nb);
p2.ndd(pb);
Ununlly, cnch cared is a container such ns u pancl ond any
card can have uny lnyout manager. p2.ndd(lb);
Constructors b.addActionlListener(this):
CurdLayout manager has the following constnictors, nb.addActionListener(this);
CardLayout( ): It creates n default Cardlayout. pb.addActionListener(this);
. Cardluyoul(int hor, int ver): It ereates u CardLayout lb.addActionListener(this);
with specilied horizontnl and vertical spuce between the C.ndd(p2, "South");
componcnts. C.ndd(p1, "Center"):
Example setTitle("Card Layout Manager"
Inport juvax.wwing. setSize(500, 250);
mport java.uwt."; setVisible(true); WindowAdapten
import java.awt.cvent. addWindowl.istencr(new
public class CardlLayoutlDemo extends Jrume
WEvente
implements Actionl.istener
public void windowClosing(Window

JLut hl, pl, bl, vl;


System.exit(0);
JBulton fb, Ib, nb, pb;
Cnrdluyout cl; y oitdeei ts4,

JPunel pl. p2:


2

0okfor tho SIA GROOP LOGo V on tho TITLE


COVERbeforo you buy
NIT-5 GUI Programming with Swing, Evont Handling and Applets 5.15
public void actionP'erlormed(ActionEvent o)

String S c.getActionCommand( ):

ir (S.cqunls("First Button"))
cl.first(p1)
clse iS.cqmls("Next Button")
cl.next(p ):
clse if (S.cqunls("Previous Button'"))
cl.previous(pl):
clse if (S.cquals("Last Button") 1
el.last(p1);

1)
public static void main(String args[

new CordLayoutDemo( ):

GridBagLayout Manager GridLayout which


layout manager. GridBaglayoul manager is similar to
GridBagLayout is the most powerful and
complex or vertically.
this layout the grid (cell) size can vary either horizontally
two-dimensional arruy, but in
it as the current layout
manager.
lays the components in a
to first create an object of GridBaglayout and set following form,
GridBagLayout is It has the
The proccdure to usea Finally, ndd these components to the layout manager.
Then set thec constraints for cach
component.
GridBagLayout( ); GridBagConstraints class.
are contained in an object of type
The constraints (properties) of eath component the cell, its alignment, the
constraints associated with it, the height and width of
following
A component can hnve the
anchor point within the cell.
placement ofa component and its
n setConstraints()
method of GridBag Layout class.
component are set using
Constraints ofa
It has the following form, GridBagConstraints cons)
setConstraints(Component comp, GridBagConstraints class,
void constraints are specificd by "cons" object of component
for which the size, placement and spacing of a nt.
Where, 'comp' is a component ficlds that can be uscd to sel
has diflerent
The GridBagConstrains class
They are as follows, Description
to be placed. The top-
Ficld/Variable the position 1or the component
These variables specily If no value is specified to
gridx, gridy position is specificd as gridx 0 and gridy =0.
let GridBagConstraint. RELATIVE.
then these arc considered as
these variables component next to the existing one.
which places the .
a cell is T hese variables are used to increase the size of
The default size of REMAINDER to these
gridwidth value is assigned as GridBagConstraint,
the cell. Ifa that it is the last component to be added in its row.
gridhcight variables, then it means
resizing of a component, il component is smaller than its cell. It
lt specifies the
fill following values.
has the
GridBagConstraints.NONE (default)
GridBagConstraints.HORIZONTAL
GridBagConstraints.VERTICAL t irthts Liw ti.
GridBagConstraints.BOTH
It specifics the
placement ol a componentwlnin a cell. 1t has following values.
anchor
GridBagConstraints.NORTH GridBag Constraints.NORTHEAST
GridBagConstraints.SOUTH GridBagConstraints.SOUTHEAST
GridBagConstrnints.EAST GridBngConstraints.SOUTHWEST
GridBagConstrainls. WEST GridBagConstraints.NORTHWESTr
sroGridBagConstraints.CENTER (default)

EMGINEERING STUDENTS SLA GROUP


WECTR JoURNAL FOR
KUM ALHN-ONE
5.16 JAVA PRoGRAMMING JNTU-HYn
AYOERABAT

of the minimum size of the


ipadx pixcls are ndded to lell ond right
ipadx, ipady
and ipady pixels are ndded to the top
nnd boltom of the component nc
the border and compone
insets This varinble specifies the empty space bctween onents.
Delnult value of insets are all zero.
whcn a container expande
These values nre used to distribute the space
-

weightx, weighty n h
are 0 then components
value ranges between 0.0 and 1.0. If the values
is dependent on the 'G
placed at the center of the container. lts belhaviour
varinble.

The program below shows the use of GridBaglLayout mannger.


Example
import java.awt.";
import javax.swing.*:
public class GridBagDemo exlends JFrame

public GridBagDemo()

Container c= gciContentPane( ): a a
br1
ttt GridBagLayout gbl - new GridBaglayout():
= new GridBagConstraints( ):
GridBagConstraints gbc
c.setLayout(gbl):
Button btnl = new Button("First Button"
gbc.weightx= 1.0; tu lba 3o barltacit Ludnteat noe t t 91 rfsrqua
gbc.weighty = 1.0;
gbc.fill GridBagConstraints.BOTH;
gbl.setConstraints(btnl. gbe);
Button btn2 = new Button("Second Button");
gbc.weightx = 1.0;
gbc.weighty= 1.0;
ya
tangbc.fill = GridBagConstraints.BOTH; bi
T gbl.setConstraints(bin2. gbe)
c.add(btn2):
seTille"GridBog Layout Manager") arstenn1ady
setSize(200, 200);
setVisible(urue);
(isis
tietrs
public static void main(String args[ })ta V sa9 br
2 new GridBagDemo( )

2et,
buttons andd set
program crealcs he twoselConstraints the propcrtics
GridBagCons
The above are set
nre using selConstraints( ) method weightx, weis
vcighty, fill using the
objcct. And thesc constraints
GROUR LOGO
7Look for the SlA on the TITLE CO
COVER before you buy
5.17
UNIT-5 GUI Programming with Swing, Event Handling and Applets
without interacting wil
Events may also be generated wnen e
5.2 EVENT HANDLING be generated
user interface. For example, an cvent may hardware
a software or
5.2.1 The Delegation Event Model mer expires, a counter reachesisa value,
completed.
lailure occurs, or an operation
024,
What is delegation event model? Explain it.
(b) Event Sources
What are its benefits? model, a source is an
object that
In the delegation event gencralcd
Answer be generated. These events arc
Delegation Event Model makes the events to
from one stalc lo
object changes
As the nanme indicates, the responsibility
of event handling
when the internal state of that one event.
called listeners. may generate more than
is assigned (delegated)
to some special interfaces another. The event sources
listeners so
Ifa listencr fails to
handle the event generated by a component,
must be registered with the event
travel through the A Source purpose each
the event dies then and there only
and does not the event. For that
that, listeners could know about
hierarchy of containers as in the earlier model. registration method.
event has its own way of
Delegation event model defincs a standard mechanism to
below,
generate and process events. In this model, component
a generates Sources of events are given
earlier). presses
an event and sends to a,listener
(with which it registered
lt generates action events when the user
an event, immediately () Button:
The listener, which is actually waiting for
pattern where a button.
receives it and processes it. This is a good design
from the cvents when the checkbox
event handling mechanism code is entirely
separated
(ii) Checkbox: It generates item
events. The advantage is selected or deselected.
useT interface components that generate the
is, without affecting the event handling
code, we can change the cevents when the uscr
interacts. (iii) Choice: Italso generates item
code of GUI (screens) with which user
delegation event model, GUI component
that makes a new choice.
In the
(link) with an appropriate when an item is double-
necds cvent handling should register (iv) List: It generates action events
is, the component delegatess clicked. It also generates item events
when item is
istener to handle its events. That user
the responsibility of event
handling to a listener. When selected or deselected.
the component, the listener
will link or register the listener with item
i5 notified which takes immediate
processing of the event. (V) Menu Item: Like list it generales both action and
model are as follows, events. Action event is generated when menu
a item is
The classes involved in this
selected and an item event is generated when a checkable
(a) Event sources
menu item is selected/desclected.
(b) Event classes
interfaces Seroll Bar: When the scroll bar is manipulated, it
(c) EventListener (vi)
(d) Adapter classes. generates adjustment events.
Benefits model.
performance than earlier (vii) Text Components: Text events are generated when the
Itgives more user enters a character.
It is easy to operate programs.
robust and flexible Window: It generates window events when a window
3. We can build more patterns. vii)
"observer pattern" in design is activated, closed, deactivated, deiconified, iconified,
It is known as
Sources, Event opened or quit.
5.2.2 Events, Event Classes
LIsteners, Event These are all the user interface components that generates
the events. In addition to these GUI components, events can
025. Write short notes on, also be generatcd by other components such as an applet.
(a) Events a26. Define Event. Give examples of events. Define
(b) Event sources. event handler. How it handles
events?
Answer: Answer
(a) Events user. In the Event
action performed by the
An event is an that shows a status
model, an event is an object when the user
Whenever a user interacts with
a GUI component, it
event
galionchanges in a source.
Events are generated Some of
enerates an event. For example, if an user
clicks over a Button,
Sate graphical user intertace. it generates an event known as
with the elements in a entering ActionEvent. Following tablc
acts pressing a button,
generate cvents are item in a list, clicking he gives components, the event they
h osvia that
keyboard, selecting an
by a user
generatc and the event handler
that handles the events. The event handler are interfaces
data ctc. These are all the events
that are gencrated
as listeners and are defined in java.awt.cvent package.
known
Se
nteracting with a user intcriace. ENdINEERINg STUDENTs SIA
GROUP
ECTRUM AIM-ONE JOURNAL FOR
JAVA PROGRAMMING IJNTU-HYDERAAR
5.18 ADI

Event Event Handler


S.No. GUI Component
ActionEvent ActionListener
1. Button, TextField.
Menu
ItemEvent ItemListener
Checkbox. Choice, List
TextEvent TextListener
TextArea
AdjustmentEvent AdjustmentListener
Scrollbar
WindowEvent WindowListener
Window
. Mouse MouseEvent MouseListener.
MouseMotionListener

Keys on Key board KeyEvent KeyListener

In the process of event handling. the component is registered with the listener implemented by the class.
Buttonrb new Button("Red");

ra b.addActionlListenert this);
this refers to the object of ActionListene When the Button rb is clicked, the ActionListener takes cares of, it and calls its
ovemidden method "actionPerformed(ActionEvent)". Itis an abstract method in ActionListener interface which can be overidden
in our class.
Event Handling
Event is an action performed by the user. These actions can be pressing a key, moving mouse, clicking mouse, pushing
burtons etc. When such an action is performed then an event is generated, such events should be handled. The process of handling
events is caled event handling. There is an approach to event handling called delegation event model.
The moderm approach for handling events is based on the delegation event model, that defines standard and consistent
mechanisms for generating and processing events. Here a 'source' generates an event and sends it to one or more 'listeners'. The
istener wats until it receives an event. After receiving the event, the listener processes it and returns. In this model, listeners
should register with a source for receiving an event notification. The advantage of this notifications are sent only to those listeners
which are interested in receiving them.
027. Write short notes on Event Listeners.
Answer:
Event Listeners
A listeneris an object which is notified when an event occurs. It must not
only register with one or more sources for rece
notifications but also must implement methods for receiving and processing those
notifications. The methods for receiving
processing events are defined in a set of interfaces found in java.awt.event.
EventListener Interfaces
Interface is a special case of an abstract class in which all methods are
abstract. An interface specifies only what to bu
not how to do. The inner details of methods are not given in an interface. Interfaces
are used by implementing in difieren lasses
EventListener Class
Eventlistener is a class which is intended to listen to the occurTence of specific
an
event, the event source has to invoke an Whenever a source
event. eined
appropriate method suitable to respond to the
by the listener. The EventListener class implements EventListener event
generated. This method iarfor uthe
interface methods, to respond
event generated. in an appropriate way
Some of the EventListener interfaces are as follows,
1. ActionListener Interface
15
This interface defines a method which is called when an action event occurs.
void actionperformed(ActionEvent ae)
AdjustmentListener Interface
This interface defines a method, which is called when an adjustment of any field occurs,
void adjustmentvaluechanged(AdjustmentEvent ac)-

3 ook for the SIA GROUP LOGO Y2 on the TTLE COVER before you buy
INIT-5 GUI Programming with Swing. Event Handling and Applets 5.19

3. ComponentListener Interface 9. MouseMotionListener Interface


This interface defines methods which are called when
This interface detals with two methods.
any component has undergone change in its size or if any the method,
component is moved from one place to another place. When a mouse is dragged then
Dragged(MouscEvent me) is called
The prototypes of the methods are. void mouse
void componentresized(ComponentEvent ce) mulüple times.
the method,
void componentmoved( ComponentEvent ce) When a mouse is moved then
void componentshown( ComponentEvent ce) mouseMoved(MouseEvent me) is called
void
void componentHidden(ComponentEvent ce) multiple times.
4. ContainerListener Interface
10. MouseWheclListener Interface
This interface defines methods which are called or moved a method, void
activated when any component is added to the container the mouse wheel is
When WheelMoved(MouseEvent me) is called. This
or removed from the container. The methods are shown mouse MouseWheelListener Interface.
below method is defined by the
void componentAdded(ContainerEvent cc) 11. TextListener Interface
void componentRemoved(ContainerEvent ce). modificd or changed a
field is
When a text area or text
textChanged(TextEvent te) is called. This
5. FocusListener Interface method, void
Gaining focus of keyboard on a component means that is defined by
TextListener Interface.
method
the keyboard is currently working on that component. WindowFocusListener Interface
which are12.
The FocusListener interface defines mcthods
focus ofkeyboard or deals with two methods.
This interface
called when any component gains
focus then a method
loses focus of' keyboard. When a window gains input
WindowFocusListener Interface is
The methods are. defined by
void focusGained(FocusEvent fe) called.
void focusLost(FocusEvent
fe) windowGainedFocus
The method is void
. ItemListener Interface itemStateChanged (ltemEvent (WindowEvent we)
It defines a method, void When a window looses its focus
then,
of an item gets changed.
ie) which is called when the state we) is
KeyListener Interface void windowLostFocus(WindowEvent
7.
methods. called.
This interface defines three
keyPressed(KeyEvent ke) WindowListener Interface
void or called when a key from 13.
invoked
This method is This interface defines several methods that deals with
keyboard is pressed.
the keyReleased(KeyEvent ke) window events.
void released after
called when a key is When a window is activated,
This method is
pressing. void windowActivated(WindowEvent we) is
keyTyped(KeyEvent ke) called.
void occur i.e., key is
character is typed three events This method When a window is deactivated,
When a
then key is released.
key is typed and pressed is entered.
pressed, the key void windowDeactivated(WindowEvent we) is
a character of
is called when called
MouseListener Interface in mouse.
8.
with the events that occur immediately When a window is opened,
This deals button is pressed and
When a mouse method. void windowOpened(WindowEvent we) is called.
released then the is invoked.
mouseClicked(MouseEvent me) When a window is closed,
void enters any component of
pointer void windowClosed(WindowEvem we) is called.
When the mouse the method,
container then called.
the Entered(MouseEvent me) is When a window is about to be closed,
void mouse pointer exits out of any component
void windowClosing(WindowEvent we) is called.
When the mouse
then, mouseExited(MouseEvent me) is called. When a window is changed into an icon,
void void windowlconified(WindowEvent
the mouse
button is pressed, is called. we) is called.
WhenmousePressed(MouseEvent me) Whern a window is changed from
void after pressing icon to window,
button is released
When mouse void windowDeiconified(WindowEvent
we) is
then, mouseReleased(MouseEvent me) is called. called.
void
ENGINEERING STUDENTS
SPECTRUM ALL-IN-ONE JOURNAL FOR SIA GROUP
5.20 JAVA PROGRAMMING JNTU-HY

Q28. What Is an ovent drivon programming and how is it structurear


NovDec
Answer 1R11,
Event Driven Programming
through mouse or keyboard called inters
ne ava event model programs provide supnort for user controlmovement are called events. The progr ms
Theactions that are performcd by the user like mouse click or mouse wi
sponsible to respond to such events are said to be event driven.
programmiung pariaigm when the even.
ne events determine the flow of program execution in event driven an as a listener forth
grams are written. The events to which the user must respond are specificd designaung onjecta response.
by parica
sent to the listener there by' inggering
CYen. ThneTelon when the event oceurs a message will be
For remaininganswerrefer Unit-V. Q27.
terface? Explaineeas
mouseListener inter
Q29. What are the mothods pported by koyListener interface and
of them with exanmples.
OR
Nov/Dec.16(R13,
How events are categorized in Java? Explain. C
OR
Discuss about handling keyboard events.
Refer Onby Topies: Key Evenis, KeyLisiener) Nov/Dec.-17(R131 C
Answer :
Java supports two types of events,
like Frame, Button. TextField etc.
(a) Semantic Events: These events are generated by software components
like Keyboard and Mouse.
(b) Low-level Events: These events are generated by hardware components
Mouse Events
mouse is in motel
Mouse events are handled by MouseListener(when mouse is stable) and MouseMotionListener(when
MouseListener
When a mouse is clicked, the mouse generates MouseEvent and is handled by MouseListener. The MouseListener inclads
five abstract methods. They are as follows,
) public abstract void mousePressed(MouseEvent e);
(ii) public abstract void moüscReleased(MouseEvent e):
e)
(iii) public abstract void mouseClicked(MouseEvent
(iv) public abstract void mouseEntered(MouseEvent e);
(v)public abstraet void mouseExited(MouseEvent e).
The following program explains the usage of above methods.
File Name: Mouselnfo.java
import java.awt.;
import java.awt.event.»;
public class Mouselnfo extends Frame implements MouseListener

setTitle("Mouse events by SNRao");


setSize(200, 200);
setVisible(true);
addMouseListener(this);
/Overriding cach abstract method of the MouseListener
public void mouseEntered(MouseEvent me)

setBackground(Color.cyan);

Whenever mouse enters the frame, the background turns to


yan.
public void mouseExited(MouseEvent me)

ok for the Sla GROUP LOGO


2 on the TITLE
COVER before you buy
setBackground(Color.orange); 5.21

/Whenever mouse comes out, the


ackground
turms to
auhlie void mousePressed(MouseEvent orang
ange.
me)

setBackground(Color.red);

IA^henever mouse is pressed,


the background
turns to red.
public void mouseReleased(MouseEvent
me)

setBackground(Color.green);

IGreen color is not noticeable as mouse


releasing action is momentary.
public void mouseClicked(MouseEvent
me)

setBackground(Color.blue):

iWhenever mouse is clicked, the background


uns to blue.
public static void main(String args[ })

new Mouselnfo( );

Amouse click is a
combination of mouse pressed and mouse released done quickly.
NbEn mouse button is released, the background changes to green and the color change may not be detected by us as it is
entary. MouseReleased is accompanied by mouseClicked by default.
Events
ey events are generated by keyboard keys and handled by KeyListener.
KrListeoer

When
ben a key is
Rehods. typed, the key generates KeyEvent and is handled by KeyListener. The KeyListener includes three abstract
They are as follows,

public abstract void keyPressed(KeyEvent e);


public abstract void keyReleased(KeyEvente)
n) public abstract void keyTyped(KeyEvent e)
The following methods
e Name:
rogram explains the usage of above
KeyInfo.java
mport java.awt.
umport
java.awt.event.";
c class KeyInfo
extends Frame implements KeyListen
public
Keylnfo()

addKeyListener(this);
setTile"Using
Key Events");
setSize(200,
200)
vetVisible(true),
methods of the key listener
publi IStart oCTIding cach of the three abstract
keyPressed(KeyEvent ke)
TRUM
ALLAN-ONE
ENGINEERING STUDENTS SIA GROUP
E J0UR
JoURNAL FOR
JAVA PROGRAMMING JNTUHYDERABAN
22 addion to hese tiour, hre s
cn be sed fir dtyg an events ie
a
contm
seBacigmá Cricezrt ACTION_FERFORMED
Toe folog ze o comstractcs of ActicnEv
ActionEveObjet sr, pe Surng cmd)

sBcigmi Coiceyeioat
ItemEvent Cass
ben a check box or 2 list boOT is cicked or wien
puibiz void ypeåkEv ie) ceciabie meu
d
S keted
r
DPes of nm as,
deseiectedd, an IemEven
t
There 2e O
rdens
yfoowing ieger consan
Bacind Coicrg
DESELECTED Te user deselected an item.
SELECTED - The user selected an inem
ItemEvet defines one more meger constants which
sigiis a change of sate ie
TEM_STATE_CHANGED
ItemEvent has the following constructor
IEvetemSelectable src, int type, Object entry. it s
The getltem( ) method is used for obtaining a referne
C30. Erpain Eferet evet to the tem which generzted an event and getitemSelectablt)
ciasses supported by
Jza is Sed for obtaining a reference to the ItemSelectable object
wnch geDeTated an event. The getStateChange ) is used far
Answa: retuning the state change for the event. The following are
Tte cizves wticb 7preser events are at ths COTe sigraturs.
o a'i ve zdg nectzzim Evt classes provide Object getitem()
a cos, ezryo-ese oears of encapsulating evenis.
Ever a n z úe rom of he Jra eert class biaachy, ItemSelectable getltemSelectable()
wch
beio.
s gezs for al evets Is consrucor is shoWD
int getStateChange()
3. InpatEvent Class
EveijeaGipa ze)
The abstract InputEvent class is a subclass
Here
oponenEvent ánda superclass of component input e
sc = Otja enerdes his evet. eyEvent and MouseEvent are its subclasses. This c
Tbe two methods hich EvetObject contains are
getSorce) 2nd toStrine ). The grSorce) method returns
es tainng
eght integer constants wnich can be used for ooa
information about any modifiers associated with tnis event
sore of the event wbeTEas, tostringl ) method retrns the string They are,
equivalert of the evenn. The AWTEvent class is a subclass ALT_MASK
of
EventObject. EventObject is a superclass of all events whereas CTRL MASK
AWTEvet is a superclass of allAWT events uhich are handled
by the delegation event model. The java.amevent package BUTTON MASK
defines different types of events wich areE generated by various BUTTON2_MASK
G.U.J elements. BUTTON3_MASK
ActionEvent Class ALT GRAPH_MASK
When a button is pressed, a menu item is selected or a lis META MASK
item is double clicked an ActionEvent is generated. This class SHIFT_MASK.
defines four integer constants which can be used to identify any
This class has following
modifiers associaled with an action event. They are, methods.
boolean isShifDown(
ALT_MASK
boolean isMetaDown(O
(i) CTRL_MASK
booleanisAlDown()
(iii) META_MASK and boolean isAlIGraphDown()
(iv) SHIFT_MASK. boolean isControlDown()

Look for the SIA GROUP LOGo 2 on the TITLE COVER before you buy
5GUI Programming with Swing. Event Handling 5.23
and Applets
FocusEvent Class
8. WindowEvent Class
When a component gains or loses input focus, a This class
FocusEve is generated. FOCUS_GAINED and FOCUS_ nere are seven types of window events.
integer constants which can be used to identily thet
OST are the inicger constants which identify these even nes
The following are those constants.
asubclass
cessi a of ComponentEvent and has the following
constructors. WINDOW_oPENED
FocusEvent(Component src, int type) WINDOW_ICONIFIED
FocusEvent(Componcnt src, int type, boolean WINDOW_DEICONIFIED
temporaryFlag) WINDOW_ACTIVATED
The is Temporary() method indicates ifthe focus change
WINDOW_DEACTIVATED
temporary. If the change is temporary it returns true clse
retums falsc. WINDOW_CLOSED
ContainerEvent Class WINDOW_CLOSING
ComponentEvent and has the
When a component is added to or removed from a This class is a subclass of
container, a ContainerEvent is generated. COMPONENT following constructor.
ADDED and COMPONENT_REMoVED are the two types WindowEvent(Window src, int type)
ofcontainer events. It is a subclass of ComponentEvent and has retum the window object
The following method is used to
tbe following constructor.
which generated the event.
ContaincrEvent(Component sre, int type, Component
Window get Window( )
Comp)
9. TextEvent Class
getContainer() and getChild( ) are its methods.
The and text areas when
These are generated by text fields
program.TEXTVALUE_
ComponentEvent Class
characlers are entered by a user or
of a component is TextEvent. The
When the size, position or visibility CHANGE is the integer constant defined by
changed, a Componentvent is generated. There are four types constructor for this class is shown below.
which
ofcomponent events. This class defines integer constants TextEvent(Object src, int type)
can be used to identify them.
10. MouseEvent Class
COMPONENT_HIDDEN defines
There are seven types of mouse events. This class
COMPONENT_MOVED can used to identify
the following integer constants which be
COMPONENT_RESIZED them.
COMPONENT_SHOWN MOUSEPRESSED
This class has the following constructor MOUSE_RELEASED
ComponentEvent(Component src, int type) MOUSE CLICKED
ContainerEvent, FocusEvent,
This class is a superclass of MOUSE_DRAGGED
classes. The
ndowEvent, MouseEvent and KeyEvent which generated ihe
MOUSE_ENTERED
O1OWing method returns the component
Cvent.
MOUSE_EXITED
MOUSE_MOVED
Component getComponent()
. AdjustmentEvent Class
The getX() and getY) methods are used to return the
five X and Y coordinates of the mouse when the event
scroll bar. There are
a occurred.
This event is generated by integer getPoint() method is used to obtain the coordinates of the
pES of adjustment events. This class defines mouse. TranslatePoint( ) method is used for changing
lor identifying
them. location of the event. getClickCount( ) method
the
obtains the
BLOCK_DECREMENT number of mouse clicks for this event. The isPopupTrigger()
BLOCK_INCREMENT method 1ests if this event causes a popup menu
to appear on
UNIT_DECREMENT this platfom.
TRACK 11. KeyEvent Class
constructor. When keyboard input occurs, a KeyEvent
This class has the following is generated.
ypC, e da There are three types of KeyEvent. Th Benerated.
AdjustmentEvent(Adjustable sre, int id, int
methods. constants are used to identify them.
This class has the following
KEY_TYPED
Adjustable getAdjustable()
KEY_PRESSED
intgetAdjustmentType(O KEY_RELEASED
int getValue() ENGINEERINO STUDENTS
*RA ALHN-ONE JoURNAL FOR SIA GROUP
5.24 a JAVA PROGHAMMI
DERABADD

program to create a frame window that


The first event occurs when a character is generated | Q32. Write a and key stro."
whercas, the next two events are generated when the key is responds to mouse clicKS trokes.
OR
pressed or released.
This class is a subclass of InputEvent and has the create a frame window
Write a program to clicks.
windas
that
following constructors. responds to mouse
Nov./Dec.-18(R16),
KeyEvent(Component src, int type, long when, int Q1D)
modifiers, int code) OR
KeyEvent(Component src, int type, long when, int
Write a program
to create a frame window hat
modifiers, int code, char ch)
responds to key strokes.
There exist some other integer coristants which are April/May-18(R16), Q11b
defined by KeyEvent. For example, VK_0 through VK 9 and Answer
VK_A through VK_Z define the ASCll cquivalents of numbers Program
and letters respectively. import java.awi.";
This class defines many methods, but the most commonly import java.awt.event.
*;
used ones are getKeychar() and getKeycode( ).
Q31. Write short notes on color and font classes
importjava.applet.";
window
/To create a frame
Answer extends Frame
public class Apln Window
Font Class
AWT provides flexibility by abstracting font manipulation mouse
operations and allowing dynamic font selection. The Font class String keystrokemsg Test the response of
clicks and key strokes";
encapsulates the fonts. Font class defines several methods and
below.
variables. Some of the important methods are listed String mousemessage
1. String getFamily() =
int mX 80, mY 80;
2. String getFontName( )
public Apln Window()
3. String getName()
4 intgetSize() addKeyListener(new MyKeyAdapter(this);
5. intgetStyle() addMouseListener(new MyMouseAdapter(this);
6. boolcan isBold() )%
). addWindowListener(new MyWindowAdapler(
7. String toString(
Color Class
name of thee font family to
The first method returns the public void draw(Graphics gr)
The second method returms
which the invoking font belongs.
font whereas the third method
the face name of the invoking
the invoking font. The fourth method gr.drawString(Keystrokemsg, 20, 60);
returns the logical name of
font and fifth method returns the
returns the size of invoking gr.drawString(mousemessage, mX, mY);
font. The sixth method returns true
style values of the invoking
BOLD style value else returns false. The
ifthe font includes the font.
string equivalent of the invoking i/To create a window
last method returns the
us to specify the desired color.
AWT color system allows various
public static void main(String args[ )
the colors. "Color' defines
Color class encapsulatesa At the same time
number of colors.
constants for specifying
our own colors using any of the Color ApinWindow aw = new AplnWindow( .
user can also createbelow.
constructors shown aw.setSize(new Dimension(400, 300)%
Color(int rgbvalue) aw.setTitle("A stand-alone AWT based Aplicat
int blue)
Color(int red, int green, aw.setVisible(true);
green, float blue)
Color(float red, float
defines various methods which help us to
The Color class getBlue() methods
), getGreen( ) and
manipulate colors, getRed( blue components offa
for obtaining the red, green and to obtain a packed
class MyKeyAdapter
extends KeyAdapter
are used getRGB() mcthod is used
respectively.
color
representation of a colorget.colorand setColor(
and changino
RGB
used for obtaining the current color AplnWindow awin;
methods are public
respectively. MyKeyAdapter{Apln Window avin)
the color
LOOk for the
IA
SIa GROUP
GkOUP LOGO on the TITLE
COVER before you buy
UNIT-5 GUTPrOgramming with Swing, Event Handling and Applets
Mouso and Koyboard Eventn
5.2.3 Handit mou
this.awin awin; to handlo
=

933. Writo Java program


koyboard ovents. Paper-11, Q10(a)
Model
public void TypedKey(KkeyEvent k) Answer:
inport java.applet.;
import ja va.awt.";
awin.keystrokemsg +-k.gctKeyChar( ): import.jnvu.awl.cvent.,
code-"IlandleMouse" width-350
awin.repaint( ); applct hcight 100>

lapplet Applet
KeyBoardMouse cxtcnds
public clnss MouselListener, KeyListener
implements
class MyMouseAdapter extends MouseAdapter

String msg" i
Apln Window awin; int mouseX=0;
public MyMouseAdapter(AplnWindow awin) int mouseY-0;
)
public void init(

this.awin = awin; addMouseListener(this);


addKeyListener(this):
mouseClicked(MouseEvent m) requestFocus( );
public void
mouseClicked(MouseEvent e)
public void
awin.mX = m.getX(O:
awin.mY = m.getY(O: mouscX=0;
Mouse is" +
awin.mousemessage= "Location of the mouseY-10;
msg="Mouse clicked!!"
awin.mX + **"+ awin.mY;
repaint( )
awin.repaint( );
mouseProssed(MouscEvent c)
public void
WindowA dapter
MyWindowAdapter extends mouseX=c.gctX( );
class mouseY=e.getY();
Window(WindowEvent w) msg="Mouse pressed!";
public void close repaint( );

Systcm.cxit(0); public void mouseRelcased(MouseEvent e)

mouseX=e.getX( ):
mouseY=e.getY( ):
Output msg"Mouse released!";
Aspheatiun
WT 1g.tced repaint( );
SLd-aha: A
and keystrokes
A

chdks
resporse of mause
Test the public void mouscEntered(MouseEvent e)

mouseX0;
mause is 76, 105 mouseY 10;
of the
catn msg"Mouse enteredil";
repaint( );

ENGINEERING STUDENTE
ALLAN-ONE JOURHAL
FOR SIA GROUP
SPECTRUM
JNTU-HYDERABA
5.26 JAVA PROGRAMMING
public void mouseExited(MouseEvent c)

mouseX=0;
mouseY=10;

msg="mouse exited!!"
repaint( )

public void keyPressed(KeyEvent e)

showStatus("Key pressed!");

public void keyReleased(keyEvent e)

showStatus("Key pressed!");

public void keyTyped(keyEvent e)

msg-msg+ e.getKeyChar( );

repaint( ):

public void paint(Graphics g)

g.drawString(msg, mouseX, mouse Y);

5.2.4 Adapter Classes

Q34. What is an adapter class? Describe about various adapter classes in detail.
OR

What is an adapter class and how you can use it to make programming the handling of events easier
O100
Model Paper-d,
OR
how can adapter classes are effective?
What is an adapter class and
Nov/Dec.-16(R13, O
Answer:
Adapter Class
override all the methods of an interface
Adapter class is de to overide to handle particular evenl.
close window tne
a
all the abstract methods of the
Window Listener interface. r e need
amely windowClosing() we are 1orced to override Even thouace.
all the remaining methods
n
of this
eride at
solution to this problem by providing adapter classes.
Java provides a By this adapter
methods of WindowListener
interiuce, We can just override our interested class we need not
method windowClosing only by usingi adt
oan
WindowListener interface. ng()
class provided for
for cach interface having more nan one
There is an adapter class abstract methods.

77Look for the Sla GROUP LOGo 2 on the TITLE COVER


before you buy
NIT-5 GUI Programming with Swing,
Event Handling and Applets
5.27
Example
WindowlListener has adapter class called
WindowAdapter. are
er erlace. There
An adapter class provides an empty implementation for all the abstract methods of an Evenll.is
even EvcntListener interluces that have adapter classes in java.awl.event package. 1hey ne
EventListener Interface Adapter Class Add Method
WindowListener WindowAdapter addWindowListener()
2. MouselListener MouscAdapter addMousel.istener()
MouscMotionlListener MouscMotionAdapter addMouscMotionl.istener()
. ComponentlListener ComponentAdapter addComponentListener(O

Containerlistener ContainerAdapter addContainerListener(O

6. FocusListener FocusAdapter addFocusListener()


KeyListener KeyAdapter addKeyListencr()
7 ItemListener, Aajun
The remaining 1our event listener interfaces namely ActionlListener,
do not have ndapler class as they have only one abstract method to
override.
Example
class to close the window.
The program below illustrate the use of WindowAdapter
import java.awt.";
import java.awt.event.":
import javax.swing.";
public class Example extends JFrame

public Example()

setTitle("Using Adapter class");


setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
HelpMe hm = new HelpMe(
);
addWindowlListener(hm);

tbntlde g)
public void paint(Graphics
Hi-point", 30, 100);
g.drawString("Hello From Nadeem Of

main(String args[]})
public static void

);
new Example(

import
java.awt.event.;
WindowAdapter
extends
class HelpMe

WindowClosing( Windowvent e)
public void

System.exit(0);

SPECTRUM ALL-IN-ONE
JOURNAL FOR ENGINEERING
STUDENTSs
SIA GROUP
TU-HYDERABAT
JAVA PROGHAMMING (JNTU-HYD
5.28
Output import java.applet.":

Usire Adapter
import java.awt.event.";
class
sapplet code = "MouseClickedDemo"
width=
300height=1
Helo From Nadeem of Hi-point lapplet
public class MouseClickedDemo extends,
Pplet

public void init()

5.2.5 Inner Classes, Anonymous Inner addMouseListener(new My


MouscAdapter(thin),
Classes
Q35. What are inner classes? How are they useful in
simplifying the code while using event adapter
classes? class MyMouse Adapter extends MouseAdapter
Answer:
Inner Classes MouseClickedDemo mcd;
We can define a class within another class and such classes public MyMouse Adapter(MouseClickeiDemo md
are known as nested classes. The nested class scope is bounded
by its enclosing class scope. If suppose class Apple is defined this.mcd = mcd;
within class Fruit, then Apple is known to fruit, but not outside
ofclass Fruit. A nested class can access to the members (includ-
ing private members) of the class in which it is nested, but the public void MouseClicked(MouseEvent mev)
enclosing class cannot access the members of the nested class.

There exists two types of nested classes i.e., static mcd.showStatus("Mouse Clicked");
and non-static. A static nested class has the 'static' modifier
applied. Since it is static, it should access the members of its
enclosing class through an object. It cannot refer to members
of its enclosing class directly. Due to this problem, we seldom Improving Above Program Using Inner Classes
use static nested classes. The 'InnerClassDemo' is the only top-level class and hs
It an inner class i.e., "MyMouse Adapter" that is defined wit
Inner class is the most important type of nested class.
is a non-static nested class. can access all
It the variables and the InnerClassDemo's scope. The InnerClass Demo ei
methods of its outer class and can refer to them directuy Just ike'Applet' and 'MyMouseAdapters' extends 'MouseAdep a
do. An inner class
other non-static members of the outer class The "MyMouseAdapter' can access all the
varnables
enclosing class.
is fully within the scope of its
methods that are present within the scope of the Inmer
To show that inner classes can simplity the code while mo' class. Thus, the showStatus( ) method can be direcu
be constructed that from MouseClicked( ) method. Therefore, it is not Te
using event adapter classes, let an applet status d
the bar of the use the reference of the applet to call showStatus() mend
displays "MouseClicked" string within is clicked. otja
browser or applet viewer when the mouse thus, there is no needto pass a reference of the invo g
Class to MyMouseA dapter(O.
Constructing this Applet Without Using Inner
and "MyMouseAdapter" importjava.applet."
The "MouseClickedDemo" program.
that are used in this The
are two top-level classes import java.awt.event. *;
h=300
"MouseClickedDemo" class exiends "Applet" and the "My. 15
applet code = "InnerClassDemo" wiou
The "Mouse- height=150
MouseAdapter" class extends "MouseAdapter". instantiates
that
ClickedDemo" class has an init() method
to that, the init() method /applet
MyMouscAdapter class. In addituon addMouseListener( pple
object as an argument to publie class InnerClassDemo extends
)
passes this'
method.
constructor obtains the applet
The MyMouseAdapter in an instance vari.
public void init()
which is stored
reference as an argument, ) method. A click of a { 70LSeAdptet
by MouseCicked(
able to be used later
showStatus( method of the applet using
the addMouselListener(new MyMous
mouse will invoke already.
that is stored
reference pf the applet

Look for the SIA GROUP LOGO on the TITLE COVER before you
INIT-5 GUI Programming with Swing. Event Handling and Applets 5.29
cluss MyMouscAdapter extends MouscAdapter
5.3 A SIMPLE SwING APPLICATION
public void MouseClickcd(MouscEvent mev) Q36. Write a simplo swing application in java.
Answer:
showStatus("Mouse Clicked"):
Program
import java.swing.*
class swingAPP

Anonymous Inner Classes


When a name is not nss ned to an inner class, it is said to Demo)
e
an Anonymous Inner Class. Usc of
anonymous inner classes
ill make the event handlers to be writen more casily. Consider Application"):
an use anonymous inner class and has the JFramejf=new JFrame("simple
applet that makes of
ome gonl to display**MouscClicked" on mouse click. jf.setSize(150, 50);
The code is as follows, jf.setDefaultCloseOperation (JFrame.
EXIT_NO_CLOSE);
import java.npplet.";
defining
import java.awt.cvent.: JLable jl = new JLable("Swing
<applet code= "Anonymous InnerClassDemo" the modernjava GUT) u
width 300 height 150> </applet>*/
jf.addG);
3
public class AnonymouslnnerClassDemo extends Applet rat isetVisible(true);
oji.setVisible(true); i
ren a i
public void init() ]
public static void main(Stringl args)
addMousecListener(new MouseAdapter()
swingUtilities.invokeLater/new Runnable()
mev)
public void MouseClickcd(MouseEvent

public void run()


showStatus("Mouse Clicked");

new Demo( );

is only one top-level


class
In the above program, there has init()
isAnonymouslnnerClassDemo', This class
dthat calls addMouseListener( ) mcthod. The argument
ncthod that
cxpression that defincs an
anonymous 1eo1"ol
assed to this method is an Output
nner class and also instantiatos it. otqnis rs to
anonymous inner clss to the Swing APP ymnt ut
The syntax that denotes an
compiler is,
defines the anony
new MouscAdapter() {..Code that Swing delining
mous inner class the modern
java GUI
will extend MouscAdapter
The anonymous innerisclassexecuted, it will instlantiate the
When the expression
6. and methods of the
Onymous inner class. All the variables by the anonymous
OnymouslnnerClassDemo are accessible
Thus, the showStatus( )
as it is within its scope.
Class
method can be called dircctly.

ETRUM ALLAN-ONE JOURNAL FOR ENdINEERING NTS

SLA GRn
5.30 JAVA PROGRAMMING IJNTU-HYDERABAnI
Afer creating this file, we can execute our hrowse
5.3.1 Applets Appletn and HTML, Securlty then lond this file, which makes "FirstApplet' to Tand
ssues, Applets and Appllcations, Pasaing In order to execute 'F'irstApplet' with an
execute
Parameters to Applets wC may
upplet vicwe
also execute the ITTMI. Iilc, I1 suppose the'1ITMI.
Q37. Explain the concopts of applets. is App.html, then the following command will run FirstApoleril
OR C:appletviewer App.lhtm.
Write about applot basics and state howit There is one more method which sinply includes a
runs In a window. Explain how an applet Itself comment at the head of Java source code file that contains the
updates its window during an informatlon APPLET' tag. Thus, our code is documented with a prototype
change. ofthe necessary HTML statements and we can test our compiled
Answer Nov./Dec.16(R13), a10 applet by starting the applet viewer with thc Java file,
Applets Example
An applet is a Java program that is embedded in HTML The following example shows this method,
document and run with the help of Java enabled browsers import java.applet.
such as, Internet Explorer. In other words, an applet is a Java import java.awt.":
program that runs in a browser. Unlike Java applications, applets <applet code= "FirstApplet" width-150height 50
don't havea main( ) method. All applets inherit the superclass
Applet. An Applet class contains several methods that helps
/applet
to control the execution of an applet. All applets must import public class FirstApplet extends Applet
java. applet and java.awt packages.
Unlike Java applications an applet does not start at main( public void paint(Graphics g)
method Applets are event driven i.c. an applet waits until an event
occurs. An applct is notified by AWT by calling event handler
g.drawString("IHello"., 20, 20);
provided by the applet. Once this is done, an applet takes appropriate
action and retums to the AWT. Below is an example to illustrate an
applet
Exomple Note
import java.awt.", Run this program with the following command,
import java.applet. C:appletviewer FirstApplet.jav.
public class FirstApplet extends Applet Applet Udating a Window when there ls Change in
Information
public void paint(Graphics g) An applet will write to the window when the AWT cali
update ) or paint() method. Apart from this applet even

update the window by itself when the information chang


EdrawString"Hello"., 10, 20): This is possiblethrough
repaint() method.
An applet can be repainted by invoking the methodre
paint). Generally, an applet the
can write in its window w
In the above program, first two lines paint) method gcts invoked
import the packages. at runtime. Ifthe appiet
The ncxt line cxtends an 'Applet' class which is Scrcen up or down, then the
in all applcts. The paint( ) method is used to draw
very important must be updated. This new informatjon in thal wr
strings can be perforn by invoking repain
applet. It has a method called drawString() that draws in an method at runtime. The
repaint) method is defined in
WT
string component class and is
Hello" at position( 10, 20) i.e., x and y pixels. Afer writing an derived from applet class.
applet, an applet is compiled in the same way as Java application The applet classcan
the execution of applet. used to invoke paint()methodd
but running of an applet is different. wind
There are fwo ways to run an applet,
will get its information Therefore, the other part o a string
vaniable and then by storing the reo d output in paintl
. invokes the repaint{ ) method. Then, he
Executing an applet within a Java-compatible web method is invoked
browser. automatícally and displaysthcoutputtnforms
tion which is storcd in a don by
using
string variable. This can be
2 Executing an applet using "applet viewer'. This executes
the applet in a window
the method drawString(
) which is defined in
pai
mcthod
forms
The repaint( )
They are as follows, method can be declarcd n Dur
To cxccute an applet using web browser, we must write
a small TML text filc which contains the appropriate (a) voidrepaint()
APPLET tag. b) void repaint(int left,
int top, int width, int n
applctcodc="FirstApplet"width 300height- 100> (c) void repaint(long
maxi.Delay)
(d) void reraintlong max Delay, he
applet int x, int y,
x, with, int
y, int w
iu
SlA GROUP LOGO 2 on the TITLE COVER boforo you buy
Look for the
5.31
UNIT-5 GUI Programming with Swing, Event Handling and Applets

(a) void repaint() public void run()


When the repaint(. method is invoked with no argu-
ments, then the entire applet window can be repainted. for:)
(b) void repaint(int left, int top, int width, int height)
When the repaint( ) mcthod is specified with the argu- try
ments such as left top, width and height, the applet
window can be repainted in specified region. These repaint( )
arguments contain only integers and they can be declared Thread.sleep(250);
in pixel. If the specified regions in window are repainted
instead of the whole applet window, the time consump- i! flag)
tion can also be reduced. break;

(c) void repaint(long maxDelay) catch(InterruptedException ex)


argu-
When the repaint() method uses the maxDelay
milliseconds can be
ment than the maximum number of
elapsed before invoking the update( method.
)

it may be invoked
While invoking repaint( method,
may efiect the updation
earlier due to some reasons. Thi maxDelay( ) method
Therefore, the
of applet window.
invoking of repaint( ) method public void stop()
can be used to delay the
upto specified milliseconds.
maxDelay, int x, int y, int width, int flag=false;
(d) void repaint(long
height) th=null;
is by us-
invoking repaint( ) methodcan delay
The other form of (which
such as maxDelay x, y (which can
ing the arguments milliseconds), public void paint(Graphics gh)
specify
the updation upto top) and
regions such as lefl andheight of
to assign the
be used specify the width and
width, height (which char
Cmessage.charAt(O);
output region). can be invoked
repaint( ) method message=message.substring(1, message.length());
Along these forms, program to demonstrate
arguments. An example message t=c;
mostly with no follows,
repaint( ) method is as gh.drawString(message, 30, 30);
Program
import java.awt.";
*;
import java.applet. Applet
RepaintExample extends Runnable HTML Code
public class implements
<applet code= "RepaintExample'" width-300
height-100>
=
"Welcome"; /applet
String message
Sample Output
Thread th;
boolean flag; AppletViewer: RepaintExample
public void init() Applet

th-null;

public void start() Welcome

Thread(this);
th=new
flag-truc;
th.start( ); Applet Started

STUDENTS
JOURNAL FOR ENGINEERING SIA GROUP
SPECTRUM ALL-IN-ONE
JAVAROaRAMMINa JNTUHYOERA.

Ayphet
eni-"A" wiih-30height s0

Nit elavx A
Pstends Apylet

NiN oil init)


s"nitialieation"
diplayt

iblie vil startç )

s-"Start
diyplayt )
A apt startad usins starti ) methad. u is
publie voil stop( )

naTgtie Mmr, an aypdet is sann using paint s"Stop"


displayt)x

An ppkt is ayad uxan shyy )ueal


Ihis mecthal is publie void display()
cai ndn any inkvrnNn
ans taur Ndr ayathn YUsYnden the avntnols
fthm theapylet System.mt.printhn(s):
An aplt
kstond using dkstvyi) methal.
is sls
autenatald tu epaint( )
calkd ndeneier wil
awser is callod,
New Bn ublid void paint(Giaphies
g)
starti
8sdawStringPaint",
Runaning 20 ,30)
sayy
start) Output
kie
A Applot Viewer:
skstryr) APplol a
Iad
nd Palnt
Figure: Applet Lite
Cyste
Applet started.
UALOok for the SlA GROUP
LoGO
on the TITLE CO
5.33
UNIT-5 GUI Programming with Swing, Event Handling and Applets
Q39. What are applet security issues?
Answer: pplet
execution o
Because java applets are run on a web user's system, there are serious restrictions on the virus or malicious coude that
may
applet may have some for
can be downloaded Irom internet and can be exccuted on our The
system.
information on our system. For this reason, we require
corrupt our sysiem iles or may collect our personal available
our system resources when an applet executes on out system.
cannot do any of the 1olowing
designers restrict the applet's functionality. As a general rule, an applet
Java
file system.
It isnot capable of performing read or write operations on the user nel uded
served the web page wnic
not allow to communicate with an internet site other than the current site that
lt does
in the applet.

It cannot run any program on the user's system.


system
It does not load programs stored on the user's
programs executable programs and shared libraries.
The stored includes example.
programs? Explain with an
differ from application
Q40. What is Java Applet? How do applets
Answer
are suitable
Java Applets from a java compatible web browser. They internet,
directly
server, transporte d over
programs which can run the
Applets are special types of javasmall applications which are accessed on an internet
for deploying web projects.
These are
automatically installed and nun as part of a web document.
programs architecture.
Applet Architecture different from console-based occur. The AWT
window-based program, its architecture will be applet waits for an event to
Since, an applet is a service routines. An should
An applet resembles a set of interupt provided by the applet. After this, the applet
Applets are event driven. handler which is repetitive
event by calling an event AWT. In situations where, an applet requires to perfom
a
notifies the applet regarding an control jo the
quickly return
take a suitable action and then starled
an additional thread of execution must be program, when the program needs
lask on its own, way around. In a windowed
other
interaction with an applet
not the not the case in applets, instead the
The user initiates input methods like readLine( ). But this is applet
and then calls some
he want. AlI these
interactions will be forwarded to theetc..
input, it will prompt the user want and however push buttoris, check boxes an
applet whenever he contain difierent controls Iike
user can interact with the Applets can also
as events to which the
applet should respond. these controls.
with
event is generated
whenever user interacts applications and applets. Applications contain main(
divided into two categories. Ihey are method and runs in a browser er.
be
Java programs can interpreter, whereas applers aoes not conlain main)
method and runs with Java Applet
Application and an
Differences between an between an application and an applet,
are the important diilerences
The following Applet
Application
programns. Applets are not stand-alone programs.
stand-alone
Applications are There is no main() method.
method exists.
The main( ) They needa browser like netscape for execution.
interpreter for execution.
They need a Java restrictions. 4. They can't access hard disk.
no hard disk accessing
4. They have 5. They need topmost security for hard disk files.
any security.
They doesn't need which is available.6. They can't share any software which is available.
any software
6. They can share software can 7. The plug-ins cannot be used by directly including
latest additions of
7 Using plug-ins browser plug-ins that are incorporated on the user's
be embededd. system
STUDENTS
SPECTRUM ALL-IN-OoNE
J0URNAL FOR ENGINEERING SIA GROUP
JAVA PROGRAMMING |JNTU-HYDERARAn
BADI
5.34
Exnmple
Examples program. import java.awt.";
An example 1or java applicalion
) import java.applet.";
import java.io."
/*<applet code = "AppletEx" width = s00 height=
class Example S00>
Vapplet>
}) public class AppletEx extends Applet
public static void main(String args[

System.out.println("Life is a climb"): public void paint(Graphics gr)

setBackground(Color.PINK)
(ii) An example for java applet program. setForeground(Color.MAGENTA)
import juva.aw."; gr.drawString("colors in Applet", 150, 200):
import java.applet.;
public class Example extends Applet
Q42. Explain briefly passin9 parameters to applets.
public void paint(Graphics gr) Answer
In HTML, an "applet" tag is used to pass parameters
gr.drawString("Life is a climb", 40, 20); to an applet. The getParameter( ) is used to retrieve these
parameters. The getParameter() method returns a value of the
given parameters in the form of string object. If integer, double
or boolean values are passed as an argument then they need to
Q41. Discuss about different applet display methods be converted from their string representation into their formats.
in brief.
Passing of parameters to an applet is shown below,
Answer: Nov./Dec.17(R16), Q11(a) Example
The applets in java are displayed in the
make use of AWT 10 Perform the
windows. They import java.awt.*;
input and output functions.
The method drawstririg() is used to import java.applet.";.
output a string to an applet.
It is the member of Graphics
class. It is called from update( )
or paint( ).
Sapplet code= "Demo" width = 400 height =100>
Syntax
param name = lontName value = SanSeri>
void drawString(String msg, param name = fontsize value 20>
intx, int y) =
Here, msg indicates the string
y. This method will
to be displayed at xand param 'name leading value = 1>
=

not detect newline characters.


specify the location of 1ext to be displayed. The x and y param name = accountEnabled valuc = tue>
The background color of the applets applet
by using setBackground().
windows can be set
The foreground color of the applets public class Demo extends
window can be set Applet
by using setForeground().
void setBackground(Color.newc) String foniName;
void setForeground(Color.newc) int fontSize;
Here, newe indicates new color. float leading
The color class has
values such as Color.blue, Color.orange, Color.yellow,
Color. boolcan active;
white, Color.gray, Color.pink etc.
public void start()
Example
setBackground(Color.pink)
setForeground(Color.magenta) String str;
The color set once can be changed when desired. OntName = getParameter("font Name
The if (fontName = = null)
curent settings of background and foreground can be obtained
using the getBackground() and getForeground(). fontName =" Not Fqund":
Color getBackground( ) str getParameter("font Size");
try
Color getForeground( )

e BLook for the SIA GROUP LOGO


2 on the TITLE COVER
bofore you buy
Programming with Swing, Event Handling and Applets 5.35
IT-5 GUI
UNIT-
ifstr!=null) g.drawOval(30,60,250,100),
fontSize Jnteger.parselnt(str);
=
g.draw Line(30, 100,30,300);
else g.drawLine(280,100,280,300),
fontSize0;
gdrawOval(30.230,250,1 50)
/Drawing a Cube
catch(NumberFormatException e) g.drawRect(600,100,200,200);
g.drawRect(700,200,200,200);
fontSize -1;
g.drawlLine(600,100,700,200);
g.drawLinc(800,100,900,200);
str getParameter( "Leading");
g.drawLine(600,300,700,400);
try
g.drawLine(800,300,900,400);
ifstr! =null)
leading Float. ValueONstr). float Value( ):
else
Output
leading=0

catch(NumberFormatException e)

leading-1;

str getParameter("account Enabled");


if(str!=null)
boolean Value( ):
active = Boolean.ValueOf(str).
Q44. What is the difference between init( ) and
public void paint{Graphics g) start() methods in an Applet? When will each
be executed?
10,20); Nov./Dec.-18(R16), Q10(a)
g.drawString("Font name:" + fontName, Answer
10,30) The difference between init() and start() method is that,
g.drawString("Font size:" + fontSize,
g.drawString"Leading:"+leading, 10,40); init() method is used to initialize all the applet variables and
petoms dnerent start-up activities. Whereas, the start(
)
10,50);
g.drawString("Account active:" +active, method is used to start and resume the applet. If the user mini-
mized and returned again to previous web page which consists
of an applet, then the execution prócess of this applet can be
resumed from start( ) method.
Write the applets to draw the Cube
and Cylinder
43. The init( ) method will be executed initially and it can
shapes. be called only once in a program. Whereas, the start( ) method
April/May-18(R16), Q10(b)
Answer will be executed multiple times during the execution ofa applet
Program program.
Q45. Write the applets to draw the Cube and
mport java.awt.*;
T shapes.
Circle
mport java.applet.*;
width=1000> Answer Nov./Doc.-18(R16), Q10(b)
pplet code= "ShapeEx.class" height-900 Program
/applet>/
import java.awt.";
public class ShapeEx extends Applet import java.applet.*;
<applet code="Shape.class" height=900 width=1000>
public void paint(Graphics g) /applet>
public class Shape extends Applet

iDrawing Cylinder
ALL-IN-ONE JOURNAL FOR
ENGINEERING STUDENTS
EROM SIAGROUP
JAVA PROGRAMMING (JNTU-HYDERARA
.36
rublic vol paint(Ciraphics g) JLaboljl D
publie void init()

/ Drawin! a Cirole
try
g drawRoundRout(40, 50, 90, 90, 100, 100),

Drawing a Cube
8wingUilites.invokeAndwait(new Runnabled
g udrawRect(h00, 100,200,200)
g draw Rect( 700,200,200,200);
public void run( )

g drawinc(600,100,700,200),
g drawine(K00,100,900,200), makeGUI);
s drawl inct00,300,700,400)
g drawlinc(800,300,900,400)
catch (cxception ex)

Output System.out.println("Unable to create


due to"tex);

private void makcGUI)

sctLayout (new FlowLayout(O):


jbal ncw JButton ("Alpha"):
jbbt new JButton ("Beta"):
jbal.addActionlListener (new ActionlList
trner()

public void actionPerformed (ActionEvent le)


5.3.2 Crenting Swing Applot, Palnting In
Bwinp. APaint Examplo
jl.sctText("Alpha is pressed");
Q46. Explain the process creating a
swing applot.
Anwer 1

The swing-tased applet is simílar to


that of AWT-bascd jbbt.nddActionl.istener(newActionListener()
applet 1Applet is a wwing based applet
AWT applet Therelore, it has
that is derived from
all the functionality thnt an applet public void actionPerformed(ActionEvent ac)
has It makes uso of methods such as init( ),
start( ). stop( ) and
destroy which the apynlet also usex. The
paint( ) method necd
not be ovemdden in »wing. The interaction jl.setText("Bcta is pressed");
with the swing applet
components is done at cvent dispatching thread
Consider the below
code of swing applet
import Javax swing addjbal):
import Java.aw1. addjbbt);
import Java.awt.event." j new JLebel"press uny button")%
addG);
applet code- "awingApplet" width- 200,height
50»
applet

In the above program, the JApplk The


public class swingApplet extends JAppletha init( ) method will ilends Applet.event
initialize the swing componens n the
dispatching thread hrough
by calling makeGUI().
Jutton jbal, innokeandwait( ). 1This is done must
In labels
be crealcd and the makeGUI) the bultons anu
Button jbbe, buttons are ndded
with aclin
the cnd the
components are added to the content pa
ok fot the SlA GROUP LOGO Y2 on tho TITLE COVER
before you buy
UNIT-5 GUI Programming 5.37
with Swing, Evont Handling
a47. Explain how and Applets
painting is done in swing.
Answer (BorderFactory.crcatel.incBorder (color. Red, 5)
Painting Setlsorder
in swing depends
upon the AWT bnsed
mechanisnm. In AWT
the paint() method
of component class
new Random( );

is used to draw the output on


lhe surface of component.
paint) is called by the runtime This (Graphics ga)
system when the component protected void paintComponent
needs to be rendered. lt can
be overridden by other applicalion
whenever the output needs to be
writlen on componenl surlace. Super.paintComponent(gr);
In swing Jcomponent inherits
components so, all the
lightweight components can inherit the int xl. yl, x2, y2;
paint( ) method. This
method cannot be overridden in int h=
getHeight);
swing because it makes use
of more sophisticated approach to paint by using int w get Width( );
the methods
such as paintcomponent( ). paintBorder()
and paintChildren( ). in getlnsets( );
=
These methods will paint tlhe specilied portion
of the component for(int = 0; i<20; it+)
i
thereby dividing the process into three parts.
The AWT paint( )
method in lightweight component will
execute the call made to
these methods in specified order. A subclass of xl = r.nextlnt(w - in.lef);
the component is
created and then paintComponent() is overridden inorder to
paint yl r.nextlnth -- in,bottom);
the surface of component. A call to super. PaintComponent( ) is -
done to override paintComponent( ). Then output that is to be x2= r.nextlnt(w ins.left);
displayed is written. protected void paintComponent(Graphics y2r.nextlnt(h ins.bottom); -

gr).Here. gr is the graphic context that holds the output that is to gr.draw Line(x1, y1, x2, y2);
bedisplaycd. The repaint() is used to make the component to be
painted under program control.
While the painting process is done the drawing in
component surface must be restricted to the area within the
border. If the output exceeds the border, swing will clip the class Demo
exceeded output. It is possible even to paint within the border but
it will get overridden when the border is drawn. Inorder to avoid
JLabel jl:
this the paintable area of the component must be compuled.
NG paintPanel p,
Area= Component size bordersize
-

Even the border widih must be obtained to adjust the ht Demo()


drawing accordingly. Border can be obtained by using getlnsets().
Insets getlnsets() JFrame jf= new JFrame("Demo ");
Inset values are obtained using the fields top, bottom, jf.setSize(250, 200);
lelt and right. They are used to compule thé drawing area jf.setDefaultCloseOperation(JFrame.
within the weight and height of component width and height
can be obtained using getWidth() and getHeight( ). Subtract EXIT_ON_CLOSE);
p.new paintPanel(
these valucs inorder to compute the usable width and weight )%

o component. jf.add(p) tto 1s


Q48. Write an example for paint in swing9 jf.setVisible(true):
Answer public static void main
(String args[ })
A simple exumple would be to paint lines toa panel. The
Cxample will create a class called paintPanel that will extend
SwingUtilities.invokeLater(new
JPancl. Runnable)
import java.awt.";
import java.awt.event."; public void run( )
import javax.swing."
import java.util. ; new
ew Demo( 08 yaa
Demo():.
),
class painPanel extends JPanel tegee kt. a
Inselsin
Random r
PaintPanel()
SPECTRUM ALLIN-ONE JOURNAL FOR ENGINEERING STUDENTE

SA GRoT
38 JAVA PROGRAMMING JNTU-HYDERABAn
Inthe above progam, the objoct of the class puint'anel The following example ereates and displays
a la
used to display the lines whose endpaints are randomly containing toth an ieon and a string. ae
nerated. The output of uhe above pvgram is shwwn belon, iuuprt java.awt.

Paint tNmo inport javas.swing.";


applet code="Labclleon" width 600, height- 40
applet
public elass Labellcon extends JApplet

public void init()

Imagelcon i- new lmagelcon("astrology gif"):


JLabel j-new JLabelCpicture". i, JLabel.CENTER
addi):

5.33 Exploring Swing Controla- JLabol and


Imagelcon, JToxtFlold Output
049. Explain lcons and labols of swing with an oxamplo.
Answer Model Paperi, Q10(D)
Applet Viewer: La.
Applet
X
lcons
In swing. icons are encapsulated
by the lmagelcon class,
which paints an icon ftom an image. Two
olits constructors are picture
shown below,
Imagelcon(String filename)
Imagelcon(URL url) Applet started
The first orne uses the image in the file names
whereas the second one use the image in thc resource "filename",| Q50. Explain various text components in JFU N
by "url" identified xamples.
The Imagelcon class implements the lcon interface OR
declares the methods as shown below. which
Explain about JTextField.
1. IntgeticonlHeight() Reer Onhy Topie TetFiclt
It returms the height of the Answer Qra
icon in pixels. Nov Dec-17(R13,
2. int getlconwildth The different detinnd
in JFC are as followskinds of text components that ar
It retums the width of the icon in
pixels.
TextFields
3. void paintlcon(Component comp,
int y)
Graphies g, int z, 2. PasswordFields
3. TextAreas.
It paints the icon at position x, y
g Additional information about on the graphics context
the paint operation TextFields
be provided in "comp". can
TextFields in swings
to swing text components. provides the funtional ui
Labels JTextFields are sn
Swing labels are instances of the JLabel class,
are used to enter
text fiends either
the text by the user fron the Ke un
extends JComponent. It can display text or/and an icon. that can be used to enter the
single line information. text or to ds
The te

Below are some of its constructors When the user CFiekdandp


an enter key, then an types the data info a
JLabellcon i) present then the event event is generated. It anhJTe
abeSring s)
is processed and the
can be used in the program.
component from package Class JTextField e
da ch
JabellSuing s, lcon i, int align) many functionalities javax.swing.te
common to swing text n
Look for the SIA GROUP LOGO 2 on the TLE COVER
before you buy
5.39
UNIT-6 GUI Programming with Swing. Event Handling and Applets
A TextField can be added to a window by adding it toa implements ActionListener
container or a panel as shown below,
JPancl new JPanel(): JPasswordField jpf,
JTextField tf= new JTextField("Input By Default public void init( )
is", 40);
Panel.add(D; try
Where, the first paramcter in JTextFicld is a string that Runnable(
SwingUtilities.invokeAnd Wait(new
is displaycd inside the textficld and the second paramcier is the
width of the textfield.
public void run( )
JTextField is a text component that is mostly uscd for
editing a single line of text in field. It makes use of Document makeGUIO:
intcrface for its model. When the user interacts with it, events
are generatcd in response.
Example
import java.awt.Flowlayout; catch(Exception e)
import javax.swing.JApplet; create since"+e);
import javax.swing.JTextField; System.out.println("Not possible to
public class TextFicld extends JApplet

publicvoid init() private void makeGUlO

setLayout(new FlowLayout( );
this.getContentPane( ).setLayout JPasswordField( );
(newFlowLayout( )) jpf= new
jpf.addActionListener(this);
JTextFieldf= new JTextField(
);

add(): Performed(ActionEvent ac)


public void action
String(passwordField.getPassword( )):
showStatus(new

2.
PasswordFields PasswordField. In the
form of Textfield is a
A special which cannot be
passwordfield, a password can be entered the
typing it. Because, 3. TextAreas
that has
bystanders when the user is as it is, instead TextAreas are used to obtain the user input
read by the user are not displayed can be created with the help of
characters entered by the echo character such as asterisk
(i.e., multiple lines. The textareas
with an
they are replacedTextficld is implemenea usingr439
JTextArea component as shown below.
JTextArea textArea = new JTextArea(6,50);
). This kind of
method is used. I/Creates a text area that has 6 lines of 50
class of swing. passwordfield, the following
Tocreate a new columns) columns each.
JPasswordField(String text, int use the number ol
A user is not restricted to1hoT of rows and
specified while
creatino noeT
Example JPasswordhield("Enter columns parameters specify only the preferred size of the
pwdfield 'columns'
JPasswordField TextArea. A user can input data that exceeds the size of the
password
password", 30); is to be used in the TextArea. When this happens the text scrolls up inorder to give
character that
The echo setEchoChar( ) method. place for additional text. Each line in the textarea will end with
using the
field can be set "n.
Example The specified rows and columns for a TextArea can,
be changed using the setRows) and setColumns() methods,
import javax.swing.
respectively.
import java.awt." In addition to that, the clipping of lines can be avoided,
java.awt.event.";
import by setting the setlLineWrap() method to 'true', as shown below.
height=100
code-"DemaJPasswordField" widh=250, textArea.setLine Wrap(true);
appiet The wrapping up of text does not effect the document,
extends JApplet
Yapplet
DemoJ Pass wordField
will first it
provide a visual effect.
public class ENdINEERINg STUDENTS SRCUP
JOURNAL FOR
AUAN-ONE
ITRUM
JAVA ABAD

5.40
Example
javax.swing."
import
import java.awt.;
java.awt.event. 100 </applet>*
import "DemoJTextArea" width = 250 height =
/applet codeDemoJTextArea
=
implements ActionListener
extends JApplet
public class

JTextArea jta;
public void init(.

try

SwingUtilities.invokeAndWait(new Runnable()

public void run()

makeGUI(O:
.

catch(Exception e)

System.out.printin(""Not possible to create since"+e):

private void makeGUI)

setLayout(new FlowLayout u);


jta = new JTextArea(6, 50);
JScrollPane sp = new JScrollPanejta);
add(scrollPane, BorderlLayout.CENTER);
jta.addActionListener(this);

public void actionPerformed(ActionEvent ae)

showStatus("n");

5:34 The Swing Buttons-JButton, JToggleButton, JCheckBox,


Q51.
JRadloButton
Discuss JButton class.
Answer a11"
Model Paper-,
JButton Class
The functionality ofthis class is to create a construct
push-button. It inherits 'Abstract
that have their arguments as an icon or a string or both. Button' class. It has three differen
rent
JButton(String s)

JButton(Icon ic)
JButton(String s, Icon ic)

00k for the SlIA GROUP LOGO Y2 on the TITLE CoVER before
you buy
UNIT-5 GUI Programming with Swing. Event Handling and Applets
5.41
will e
An ActionEvent will be generated, cach time when a button is pressed. The button's 'action commandhs defincd
obtained when the object of ActionEvent class is passed as an argument to the method caled octionperfome et action
in 'ActionListener' class. The 'action command' string will be displayed inside the button as a defaut.
command seLActionCommand() or getActionCommand( ) methods respectively, can be called. Their
n can be done as.
declaration can
String getActioncommand( ).
are used within an applicao
For each button, there will be a different action command thus, when multiple buttons
button that is pressed can be 1lound out using its action command.
Example
import java.awt.";
import java.awt.event.";
import javax.swing.*
*"300">
<applet code = "ToolBarApplet.class" width = "300" height=
</applet>*
public class ToolBarApplet extends JApplet

public void init()

EventQueue.invokeLater(new Runnable( )

public void run()


ToolBarFrame( );
ToolBarFrame frame = new
frame.setTitle("ToolBarFrame")
DEFAULT_HEIGHT");
frame.setSize("DEFAULT_WIDTH,
frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
frame.setVisible(true)
A

extends JFrame
class ToolBarFrame
))
public ToolBarFrame(
in ToolBar1
WAction objects of buttons new Imagelcon("new.gif");
newAction = new ButtonAction("New,
Action new Imagelcon("open.gi")
openAction = new ButtonAction("Open",
Action new Imagelcon("close.gir)
closeAction new AbstractAction("ose,
Action
actionPerformed(ActionEvent ae)
public void 3

System.exit(O);

Value(Action.SHORT_DESCRIPTION, "Close"):
CloseAction.put new Imagelcon("save.gi)
saveAction = new ButtonAction("save,
Action
ToolBar2
/3action objects of new Imagelcon("cut.gif")%
Action = new ButtonAction("Cut",
= new ButtonAction("Copy", new Imagelcon("copv oirmls
Action copyAction
Aetion paste Action = new ButtonAction(Paste, new Imagelcon("paste,gif")

IButton of ToolBarl
FOR ENGINEERINa STUDENT
PECTROM ALL-IN-ONE JGURNAL SIAGROTP
JAVA PROGRAMMING (JNTU-HYDERAR
5.42 BADI
JButton newButton = new JButton(newAction);
JButton openButton= new JButton(openAction);
JButton saveButton = new JButton(saveAction);
JButton closeButton = new JButton(closeAction);
Populating ToolBarl
=
JToolBar jtbl new JToolBar( );
jtbl.add(newButton);
jtbl.add(openButton);
jtbl.add(saveButton);
jitb1.addSeparator( );
jtbl.add(closcButton); A
addjtb1,BorderLayout.NORTH);
IPopulating ToolBar2
JToolBar jtb2 = new JToolBar();
jtb2.add(cutAction);
jtb2.add(copyAction);
addGtb2, BorderLayout.SOUTH);

public static final int DEFAULT_WIDTH = 300;


public static final int DEFAULT_HEIGHT= 300;
class ButtonAction extends AbstractAction

public ButtonAction(String name, Icon icon)

put Value(Action.NAME, name)


put Value(Action.SMALL_ICON, icon)

public void actionPerformed(ActionEvent,ae)

System.out.println(get Value(Action.NAME)
+"Button is pressed");

Q52. Discuss about JToggleButton.


Answer 7 111 o
JToggleButton adol Paper-l, Q110)
Model Paper-ll, Q

JToggleButton looks similar to that


When this button is pressed it remains as
of JButton but the functionality
pressed rather than popping of it differs. It has two release.
It gets released on the second push. back. In
states namely push anu
That is it toggles between states order to release it in again.
for each button the user should prE
Toggle buttons are the objects of class press.
JToggleButton. The classes
it. JTog utton generates an action event when it is such as JCheckBox rivedfhrom
pressed. But it generates and JRadioButton are detion is
used. When the toggle button is pressed selection an item event when or s
is perlormed and
when it is pressed the concept 0fder
to handle the item events, the interiace called again de-selection is performe
llemLIStener must be implemented.
(i) itemStateChanged( )
(ii) getltem( )
ros tal aysmi 'or
Methods of this interface are as 101

(ii) isSelected()
The constructor of JToggleBulton is as follows,
huki
JToggle(Button(string str))
iet"Rtea ot ut
Here, str indicates the string to be contained in JToggleButton.

ATLOok for the SIA GROUP LOGO 2 onithe TITLE coVER before you buy
5.43
UNIT 6 QUI Programmlng with Gwing, vent Handling and Appets
Javax,wing.JConponent
Expple
impot jaVa.aWI,"
impot javax uwing
Javax.nwlng.Abairacillutton
import jnva,awl.event.
publie olan "Topglellutton extonda JApplot
Juvax.nwing.Togglclutton
publiebutton()

Contaner c potContentP'net javux.swing.JRadiolButton


System.out.printne"Are you Indiun") n javax.Wing.JCheckBox
JChockBox nnd
JRndloButton
DuttonGroup bg - new DuttonGroup( ): lguro: llerarchy of
JTogglelutton ]
th new Jlogglelutton |
Example
import java.wwing.";
new JTogglebutton("Yo»"):
innport java.awi,"
new Jlogglelutton("No"): juva,awt.eveint,"
import implements
JCBIDemo extends JFrume
C.8etlayout(now llowl.ayout( ) publie elass
tb,length;i)
i
leml.istcner
Tor(int 0;i

g.ndd(tbi
JToxtField toxt; tu
JCheckBox cbl, cb2, cb3;
c.ndd(tbi):
public JCBDemo()

ContaineregetContentPane(
Output C.sctlayout(new Flowl.ayout( ):
textncw JTexticld("See Effect of Checkboxes
Applet Here", 30)
c.add(text)
Are you an
Indian? chl new JCheckBox("SanSeril");
c.add(cbD;
Y orn 11 ch2 new JCheckBox("Bold");
c.add(ch2)
controls,
tho followlng In swlng cb3 new JChcckBox("Italic");:
Q53. Explaln c.add(cb3);
(1)
JChockBox
JRadloButton. cbl.nddltemlListcner(this):
(11)
,OR cb2.nddlteml.istener(this);
boxos.
about applylng chock ch3.adlteml.istener(this):
DoBcribo nddWindowl.istener(new WindowAdapter(O
7ople JChekhox
Refer Only Nov /Dec17(R13), Q0(a)
public void windowClosing (WindowEvent e)
Answer
JChecklox that provides
() nwing GUI conponent two stnteC System.exit(0)
JCheckBox is n have
A
a checkbOx. Checkboxcs
functionality of falsc)
he
selected or not (true or JCheckJJox class which set'Title("Using JCheckBox class'"):
Le., crented usiPg
Checkboxcs nre of JChcckBo and
of
JTogle)ulton. Ierarchy cxamla
below. lere is an mf
actSize(400, 200):
is subelaxs in thc figure the
ís shown
Jadioluttoncheckboxen the text hn per
nia Tmalin public void itemStateChanged(ltemlEvent
of creatingBelocted c) psie
checkbox JOURMAL EMOINEERINO STUDENTS
AL POR
SPECTRUM
MLLIN-ONE
SIA
GROUP
DERABA
5.44 JAVA PROGRAMMING [JNTU-HYDE
Example
String fname =" import javax.swing."
int b 0, i 0 import java.awi.";
import java.awt.cvent.";
ifcb1.isSelected()
im
public class JRBDemo extends JFrame implemeny
fname= "SanSerif": ItemListener
clse
fname ="Monospace"; JRadioButton rbl, rb2, rb3, rb4, rb5;
ifcb2.isSelected( )) public JRBDemo()

else
b Font.Bold, . lo rast
Containerc = getContentPane( O:

c.setLayout(new Flowl.ayout( ),
b=Font.PLAIN; *

ButtonGroup grp = new ButtonGroup( ):


ifcb3.isSclected( ))
rbl new JRadioButton("S.S.C")
i= Font.ITALIC; rb2 new JRadioButton("Intermediate");
clse rb3 new JRadioButton("Graduate");
i= Font.PLAIN; rb4 new JRadioButton(Post Graduate")
Font f new font (fname, b+i, 15); rbsnew JRadioButton("Others");
text.setFont(); grp.add(rbl;
grp.add(rb2);
gp.add(rb3)
public static void main(String argsi[ ])
Brp.add(rb4)
grp.add(rb5);
new JCBDemo();
C.add(rbl):
C.add(rb2)
c.add(rb3);
c.add(rb4);
The above program creates three checkboxes as SanSerif, c.add(rb5);
Bold and Italic by creating objects of JCheckBox class. If any rbl.addltemListener(this)
checkbox is selected then its state is checked using is Selected() rb2.addltemListener(this)
method that returms cither true or false and then text is displayed
as per the checkbox selected. rb3.addltemListener(this)
rb4.additemListener(this)
:
(1i) JRadioButton
rb5.addltemlListener(this)
Radio buttons are created using JRadioButton class,
which are similar to check boxes that is they also have two add WindowListener(new
group of WindowAdap
states selected or deselected. Radio buttons are
buttons from which only one radio button can be selected at any
public void windowClosing(WindowEEvente)
time. Sclecting other radio button makes the previous selected
radio button to be deselected automatically. JRadioßutton
class is a subclass of JToggleButton class. The grouping of the System.exit(0);
Tadio button is made by adding the JKndioButon object to a
ButtonGroup object that takes Care ol the state of the buttons
in the group.
group of radio butto setTitle"ereating
The following program crealesa setSize(400,
RadioButtons")
message when a radio
and displays an appropriate ton i 200),
setVisible(true):
selected.

Look for tho SlA


GROUP LO00
V on the TITLECOVER
hefnre yÖu hi
iINIT-5 GUI Programming with Swing. Event Handing and Applets
UNI
public void
itemStateChanged(ItemEvent e) show(e):

string str =" ";


setTitle("PopupMenu"):
ifrbl.isSelected( ))

str "S.S.C";
= setSize(30, 300):
ifrb2.isSelected(O) setVisible(true);
else
str= "Intermediate"; c)
void show(MouseEvent
else ifrb3.is Selected(
D)

str= "Graduate"; iffe.isPopupTrigger( ) c-getY(O%


else ifrb4.isSelected(0) popup.show(e.getComponcnt(), c.getX().
str="Post Graduate";
main(String args[ })
else if (rb5.isSelected( ) public static void
str = "Others";
JOptionPane.showMessageDialog(null, "your new PopupMenu( ):
qualification is" + str);

public static void main(String args[ ]) JScrolIPane, JList,


5.3.5 JTabbedPane,
JComboBox
new JRBDemo( ); control.
Q55. Explain the tabbed panes swing
Model Paper-, a11(b)
Answer :
buttons and adds
The above program creates five radio Tabbed Pane
them to the ButtonGroup object "grp". The last
statement prints
A tabbed pane is a component
which appears as a group
Every folder has a title. The
contents
an appropriate message when radio a
button is selected.
of folders in a file cabinet. selected. Only one folder can
Q54. With a program, explain how to create popup become visible when a folder is
be selected at a time. Tabbed panes
are encapsulated by the
menu's in Swing.
Nov/Dec.-16(R13), Q11(b) JTappedPane class, which extends JComponent.
Answer :
import javax.swing.*;
Example
import javax.swing";
import java.awt.event.";
import java.awt."; /<applet code = "JTabbedPaneExam" width 500
public class PopupMenu extends
JFrame height= 100>
/applet zrmhcilci or nice.0
JPopupMenu pm; public class JTabbedPaneExam extends JApplet
public PopupMenu()
o
public void init()
Container c= getContentPane( ); 93189e
aralbiem
pm new JPopupMenu( ); TabbedPane j new JTabbedPane( );
/add menu items to popup
so :
pm.add(new JMenultem("undo"));
j.addTab"Family", new FamilyPanel(
));
j.addTab"Friends", new FriendPanel(
pm.add(newJMenultem("redo")); );
jaddTab"Relatives"new RelativesPanel(
pm.addSeparator( ); getContentPane(,).addO)%i ))
pm.add(new JMenultem("cut"): orjeti
pm.add(newJMenultem("copy");
pm.add(new JMenultem(""paste");
C.addMouseListener(newMouseAdapter() class FamilyPanel extends
JPane) e
c) public FamilyPanel(O
public void mouseReleased(MouseEvent
a snov
dve
PECTRUM ALIN-ONE JOURNAL FOR EHCINEERING STUDENTS
SIA GROUR
JAVAPROGRAMMING JNTU-HYDERABAD
AD
JButton bl = new JButton("Ram Reddy");
add(b1);
JButton b2= new JButton("Krishna Reddy");
add(b2):
JButton b3 = new JButton("Srinivas Reddy"):
add(b3);

class FriendsPanel extends JPanelte

public FriendsPanel()

JCheckBox cbl = new JCheckBox("Srinu"):


add(cbl:
JCheckBoxchb2= new JCheckBoxVenka:
add(cb2):
JCheckBox cb3 = new JCheckBox("Prasad");
add(cb3);

class RelativesPanel extends


JPanelakace
public RelativesPanel()

JComboBoxC = new JComboBox(


);
cjaddltem("Arvind");
cj.addltem(Anu");
cj.addltem("Krishna");
add(c); iginaza

Q56. Explain the following,


(a) JScrollPane
(b) Combo Boxes.
t
Answer:
(a) JScrollPane Nov/Dec.-17(R1J), O11
A scrollpane is a component
implemented in swing which provides a rectangular
by the Jscrollrane class, area in which
wnicn extends the component can be viewed. uncs a
provided if required. JComponent. Horizontal
Example
Scrolo
and/or vertical scroll bars ca" also

import java.awt.;
import javax.swing.;
<applet code = "ScrolIPaneDemo" width = 300 height= 400>
/applep/
trearmi2.
public class ScrollPaneDemo extends JApplet
oirgMur
public void init() a fuine sidu

Look fr the SIA GROUP LOG' V2 on the TimLE COVER


before vou buy
#
INIT-5 GUI Programming with Swing. Event Handling and Applets
Container contPane getConlentPane( ):
contentPane.setlayout(new Borderlayout ( )
JPaneljp new JPonel(0:
ip.setL.ayout(new GridlLayout (20, 20):
ints-0;
for(int i0; i< 20; it+)

for(int j- 0;j < 20:jt+)

jp.add(new JButton("Button" +s);


+s;

SCROLLBAR_AS_NEEDED;
int I= ScrollPaneConstants.VERTICAL_
SCROLLBAR_AS_NEEDED;
int m = ScrollPaneConstants.HORI-ZONTAL_
JScrollPane jsp = new JScrollPaneip. m);
1,

contentPane.add(jsp, BorderlLayout.CENTER);

(b) Combo Boxes


For answer refer Unit-V, Q58.
Q57. Discuss about JList.
Answer
scrollbars the list
JList But it is possible to create a scrolling list. With
a list without any scrollbars.
By default, JList its creates t
or both as necessary.
can be scrolled horizontally, vertically tofttoutt

. Scrollable list can be created


Pass the JList object to the
JScrollPane spane = new
the JList the
in two ways, they are,
JScrolIPane constructor.
JScrollPane(JListobject);
viewport view of a JScrollPane in two
steps.
2. Make
JScrollPane in two steps.
JScrollPane( );
JScrollPane spane = new ).setView(JListobject);
Spane.getViewPort(
Example
creates a scrollbar list
The following example
import javax.swing.*
import java.awt. ";
import java.awt.cvent.°;
ScrollableLíst extends JFrame
public class
"White", "Pink")
colors[ ] = ("Red", "Black",
String
JList list;
JScrollPane spane; 3
getContentPane( );
Containerc=
JList(colors); lcreate a list
list new
SelectionModel(ListSclectionModel.SINGLE_SELECTION):
list.sct
FOR ERGINEERINO
STUDENTS
PECTRUM ALLAN-ONE J0URNAL SIA GROUP
JAVA PROGRAMMING (JNTU-HYDERARA
48
new JScrolIPane(list); I/Scrollable list C.add(cb);
spane
c.add(spane) c.add(text)
addWindowListener(new WindowAdapter() addWindowListener(new WindowAdapter()

public void WindowClosing(WindowEvent we) public void windowClosing( WindowEvent e

System.exit(0): System.exit(0);

setTitle("CreateScrollableList");
setTitle("Creating Combo box");
setSize(300, 350);
setSize(400, 200):
setVisible(truc);
setVisible(true);

public static void main(String args[


})
])
public static void main(String args[
new ScrollablelList():
);
new JComboBoxDemo(

Q58.Explain the swing control ComboBox.


Answer
class HelperListener implements ItemListener
ComboBox
providesa list of items
A combo box (or a drop-down list)
box is
from which user can select any one of the item. combo
A
JTextField jtext;
JComponent
created using JComboBox class, which inherits the HelperListener(JTextField j)
class.
JComboBox is similar to choice component ofAWT. An
) method. The
item is added to a combobox using an addltem( jtext=j:
JComboBox class.
program below illustrates the use of
mport Javax.swing.":
public void itemStateChanged(ltemEvent e)
import java.awi.
import java.awt.event.";
JFrame String str = (String)e-getltem( );
public class JComboBoxDemo extends
jtext.setTex(°You Selected" + str);
JComboBox cb;
JTextField text;
T
public JComboBoxDemo() In the above program, combo box is created eithe
using3

JComboBox class. Items to the combo box can be ied


getContentPane):
Container c = by adding items individually using addltem( ) methoa oy
c.setlLayout(new Flow Layout( ): an array of string in the JComboBox constructor
{"ldly". "Dosa", "Wada");
com
String array[ ]= The above program displays all the items of a y
text
new JTextField"My Choice", 20): bOx. We can restrict the
number of items to be d
JComboBox(array); adding the following statement.
cb new
cb.addltem("Puri"); cb.setMaximumRowCount(4): com
cb.addltem("Puri"): crollthe
t displays only 4 items and the user can serol
box to select other items.
addltem("Coffce"); nts a*
cb HelperlListener{text); Combo box generates item events and these
hl = new
Helperlistener tenet.
handled using a separate class called HclperLiSte
cbaddltemlistener(hl):
IA GROUP
the SIA
LOGO Ao
YE onthe TITLE COVER before you buy
*LOokfor
UNIT-5 GUI Programming with Swing, Event Handling and Applets 5.49

059. Discuss about list, panels. fruits.add("Apple"):


JMenultem(""Mango
Answer Nov./Dec.-17(R13), Q9(b) tJMenultem il - new JMenultem("Grapes")
JMenultem i2 new
List fruits.add(i):
For answer refer Unit-V, Q57. fruits.add i2):
fruits.addseparator( ):
Panel
JRadioButtonMenultem i3
-

For answet refer Unit-V, Q20, Topic: JPanel. JRadioButtonMenultem("Papaya");


new =
5.3.6 Swing Menus, Dlalogs d t theatres.add(13);
mb.add(fruits);
JMenu("Flowers")
Q60. Write in brief about JMenuBar. JMenu flowers = new
Modol Paper-il, Q11(b) flowers.setMnemonic(°F°);
Answer JMenultem("Rose"):
JMenuBar final JMenultem i4=new
JMenultem("Marigold");
JMenuBar is derived from JComponent. It contains a JMenultem i5=new
list of menus. Every application has a menu bar which empty
is
Initially the user need to add desired menus to it before is used.
it
main(String args[ )
It defines several public static void
It has only one constructor which is default.
methods such as given as follows:
new Demo( );
JMenu add(JMenu menu)
menu bar. It
This method is used to add a JMenu to the
menus
returms a reference of the menu that is added. The
are added in left to right order. Output
index)
2. Component add(Component menu, int
at specific.location.
This function is used to add a menu
a

It is derived from the container.


The index begins at 0,
Apple
which will be the left most menu. Mango
menu)
3. void remove (component Grapes
remove the menu to which a
This metod is used to oPapayaa
reference is provided.
4. void remove(int index) at the
remove the menu present
This method is used to
specified index. Q61. Explaln the following,
getMenuCount() ( JMenu
5. of elements
to get the number (ii) JMenultem.
This method is used bar.
contained in the menu Answer
intsetJmenuBar(JmenuBar mbar) JMenu
specified
the menubar at the
6.
used to place JMenu indicates a menu in the menu bar. It contains a list
This method is
position. of JMenultems. A JMenu can be a part of (i.e., submenu) another
JMenu. Hence, it is derived from JMenultem. Constructor of
ELample
JMenu is as follows,
import javax.swing.";
JMenu(string name)
import java.awt.";
java.awt.event."; The above constructor creates a menu with the specified
import name. It will be empty initially. The user need to add menu items
inport java.util." extends JFrame to it. Methods of JMenu are as follows,
public class Demo 1. JMenultem add(JMenultem item)
This method is used to add the specified menu item
public Demo() menu. The items will be added at the end of
to the
the menu.
JMenuBar( ); It relurns a reference to the added item.
JMenuBar mb = new
setJMenuBar(mb); 2. JMenultem add(Component item, int index))
Pane( );
FinalContainer co getContent This method is used to add the item at the
specified index.
new JMenu("fruits"); It returns a reference to the added
item.
-SIA
=
JMenu fruits
ENINEERING.STUDENTS
PECTRUM ALLAN-ONE JOURNAL FOR GROUP
JAVA FHO DERABA
5.50
Output
3. void addSeparator()
This method is wed to adda viual separator to the
me
Numbers3
The scparator will be added at the end of the menu.

4. void inertSeparator(int indez)


This method is used to add a vísual separator at thec
specified index in the menu
void removefJMenultem menu) D

This method is used to remove the specified item from


the menu. Reference to the item to be removed will be
prurvided to it.
void removeint inder1) (ii) JMenultem
JMenu
This method is used to remove the item present at the JMenultem represents an clement in the
or it causes anothe
spectfied index. linked with a program action menu
the t
It is considered aS a special type of button
7. int getMenuComponentCount( ) be displayed.
An action event will be generated
This method is used to get the number of items contained derived from AbstraciButton.
is pressed. Ihe mostly used constne
in the men ach time the button
defined by it is as follows,
8. Component[ JgetMenu Components( )

JMenultem(string name)
This function is used to get the items contained in the
meTIu
JMenultem(icon image)
Exmpe JMenultem(string name, icon image)
Lmport javaz.swing. JMenultem(string name, int mn)
iTportjava.awt" JMenultem(Action action)
mport java.awieveTt"; This constructor creates a menu nem with the specified

pble cesdemoctads JFrame implements ActionlisteTET as follows,


ttributes. The methods of this class are
. void setEnabled(boolean b)
public static void main(Stringt ] args)
This method is used to enable or disable the menu
item

protected void init(string text, icon icon)


private JMenuBar mb = new JMenuBar( ); with te
This method is used to initialize the menu item
private JMenu mi = new JMemu"Alphabets"); given text and icon.
private JMenu m2= new JMenu("Numbers"): . void AddMenuKeyListener(MenyKey Listenerm)
menuBar.add(ml}
menuBaraddém2);°e o3 ninia rao This method is used to add a MenuKeyListener to
te

menu item..
JMenultem il = new JMeultem("A"):
protected string paramstring( )
JMenultem i2 = new IMenultem("B")
This method is used to return the string representatid
JMenultem i3 = new JMenultem("C")
of the menu item.
JMenultem 4 = new JMenultem("D");
void setModel(ButtonModel newModel)
miaddil
ml addfi2) s et4g This method is used to set the model represented by
button.
mIadd(i3)
ml addi4)
6. void setArmed(boolean b)

JMenultem is = new JMenultem("1"): This method is used to set the menu item as a
SMenultem is = new JMenultem(2") Q62. Discuss how JDialog is used.
JMenultem i7 = new JMemultem("3"); Answer
JMenultem i8 new JMenultem("4" JDialog
m2addis), JDialog is a type swing class that is used tocreatcre
m2addib):
of contai
dialog. It does not inherit
Jcomponent. It is a 1op-levelo
makesas
m2.addi7), which is hedvy in its weight
than others. JOpto na
m2add(8), of JDialog for creating dialogs. It features to
3tt itlurs Jframe and it can be
has similar
frame is
dae
created and managed a a. compon
It is inherited from
AWT classes such as conla
window and dialog.

Look (or the SA dRoUP LOGO Y2 on the


TITLE COVER
before you buy
INIT-6 GUI Programming with Swing, Evont Handling and
U Applets
5.51
using
The layout managcr and the sizc of a JDinlog can be set by the user. The windows of can be hiduc
it nauses the
Visible ) method. It also allows to ndd a menmu bar to it. JDialog can be cither modal or modeless. A modal dialog pat
user to
aplication if the shalog closed. A modeless dlialog activates the remaining parts of the npplication. Judialog allows the
is
creatc any type of dhalo8. Steps tor creating a JDinlog are as follows,

Construct an object of type JDialog


Determine the properties for the dialog such as size, layout manager nnd default close policy.
2
3 Extend the content pane of the dialog by adding the components.
4. Make thhedinlog visible by making use of setVisible(true) method.
A dinlog can be rernmoved from the sereen by making use of
set Visible( falsc) or dispose( )methods. Thesc mci
method setVisibietais
derived from window. When a dalog is most lrequently used by an application then the in th
method when called will delete the dialog from view. When a dialog does not have much chancc to be displuye
released. One or e
aior
metlhocd dispose()1s used. Thus icthod when called wvill cause the resources of a dialog to get
the
constructor defined this dinlog is as follows,
JDinlog(frame parent, string title, boolean isModal) dialog. Ana tnc
The title indicates the title of the
In the above statement, the parent
indicates the owner of the dinlog. modal onerw
or modeless. It will be passed, The values true if the dialog is
fodal indicates thhe type ot dinlog whether
modal
is modeless.
the valuc talse is passed if the dialog

Example
import java.awt."; anageit
import javax.swing.:
import java.awt.event.";
implements Actionl.istener
public class Dialog extends JApplet

dialog");
JLabel jl= new JLabel("enter the
JTextficld jt= new JTextficld(20);
JButton("ShowDinlog"):
JButton jb= new
JBufton("OK");
JButton jb l = new
JButton jb2 new JButton("Cancel");
=
JDialog((Frame) null, "Dialog", truc);
private JDialog jd= new
)
public void run(

getContentPanc()
Container c =
jd.getContentPane( );
Container cl =

C.setlLayoul(new flowLayout( ):

c.addjb):
cl.setLayout(new MowLayout(%
cl.addg):
cl.addjt);:
ol.addjb1):
cl.addgb2)
jb.addActionlL.istener(this);
jbl.addActionl.istener(this):
jb2.addActionl.istener(this);

STUDENTS=
RGM ALL-IN-ONE JOURNAL FOR
ENdINEERING -
SIA GROUP
DERABAN
5.82
public void actionPerformed(actionEvent ac)

if(ac.getSource( )= =jb)
jd.setBounds(200, 200, 200, 160):
jd.show( :

clse ifac.getSourcet) =-jbl)

showStatus (Gt.getText(O):
jd.dispose( )

clse if (ac.getSource( )- =jb2)

showStatus("you have pressed cancel");

jd.dispose( ;

Output
Appletviewer: Dialog
OO
Applet

Show dialog

Dialog
Enter the Dialog

Hello

OK Cancel

Java Applet Window

3Look for the SIA GROUP LOGO


on the TITLE COVER before youbuy
T.5
NIT-E GUI Programming with Swing. Event Handling and
Applets
6.53
k3. Explain
the process of creating modeless dialog.
nswer:
aining
Amodeless dialog can be created using JDialog. The JDialog by default creates a modcless dialog. It allows the will
w
user input hatt
plication to be in active state. This model is used when the remaining application does not depend on the
t

ven in the dialog. The constructor for creating a modeless dialog is as follows,
JDialog(frame parent, string title)
exampIc
A photo touch up is the best
In the above statement, parent indicate the owner of the dialog with specified title. interactively wiuou
is allowed to change the filter
e
modeless dialog. It allow several touchup filters to be selected. The user used tiey provcu
reopen the dialog. Generally, the dialogs are modal, where the modeless dialogs are
need to close and then
y

useful.
be very much an application betore
in
window to another window
Generally, the modeless dialogs allow the user to switch from one
sclosed.

Erample

import java.awt.Dialog;

import java.awt.flowLayout;

import javax.swing.JDialog;

import javax.swing.JFrame;

public class ModelessDialog

main(String[ ]args)
public static void

JFrame("parent frame");
final JFrame jf= new
jf.setLayout(new flowLayout( );
jf.setDefaultCloseOperation(JFrame.EXIT_CLOSE);

200);
jf.setBounds(100, 100, 200,
jf.setVisible(true);
JDialogif, "Modeless Dialog");
JDialog jd = new
200);
jd.setBounds(100, 100, 200,
jd.setVisible(True); Dialog.ModalityType.DOCUMENT MOnAT
"DocumentMouaiDlalog, L);
= new JDialog01,
JDialog id1
100);
JD2.SETBOUNDS(200, 200, 200,
"MODELESSDIALOG2
JDIALOG(JD2,
NEW
JDIALOG JD2 =
100);
JD2.SETBOUNDS(300, 300, 200,
JDI.SETVISIBLE(TRUE);
JD2.SETVISIBLE(TRUE);

ENGINEERING STUDENTS SIA GRoUP


SPECTR
RUM ALL-IN-ONE JoURNAL
FOR 2

You might also like