Java Unit 5 Spectrum
Java Unit 5 Spectrum
5
SIA GROUP
PART-A
SHORT QUESTIONS WITH SOLUTIONS
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.
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
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
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
PART-B
ESSAY QUESTIONS WITH SOLUTIONS
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
Containcr
JComponent
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
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
ADplet staled.
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,
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
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( ):
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.
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
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
setBackground(Color.cyan);
setBackground(Color.red);
setBackground(Color.green);
setBackground(Color.blue):
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,
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
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(
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( )
showStatus("Key pressed!");
showStatus("Key pressed!");
msg-msg+ e.getKeyChar( );
repaint( ):
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.
public Example()
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
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
new Demo( );
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
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;
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
s-"Start
diyplayt )
A apt startad usins starti ) methad. u is
publie voil stop( )
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>
=
catch(NumberFormatException e)
leading-1;
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)
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
-
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.
setLayout(new FlowLayout( );
this.getContentPane( ).setLayout JPasswordField( );
(newFlowLayout( )) jpf= new
jpf.addActionListener(this);
JTextFieldf= new JTextField(
);
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()
makeGUI(O:
.
catch(Exception e)
showStatus("n");
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
EventQueue.invokeLater(new Runnable( )
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);
System.out.println(get Value(Action.NAME)
+"Button is pressed");
(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()
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; *
str "S.S.C";
= setSize(30, 300):
ifrb2.isSelected(O) setVisible(true);
else
str= "Intermediate"; c)
void show(MouseEvent
else ifrb3.is Selected(
D)
public FriendsPanel()
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
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);
System.exit(0): System.exit(0);
setTitle("CreateScrollableList");
setTitle("Creating Combo box");
setSize(300, 350);
setSize(400, 200):
setVisible(truc);
setVisible(true);
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
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.
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( :
showStatus (Gt.getText(O):
jd.dispose( )
jd.dispose( ;
Output
Appletviewer: Dialog
OO
Applet
Show dialog
Dialog
Enter the Dialog
Hello
OK Cancel
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;
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);