I I
I DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING STAFF NAME: S.Rajini
CLASS: III /CSE
SUBJECT CODE: CS2305
SEM:V
SUEJECT NAME: Programming Paradigms
UNIT-3 EVENT-DRIVEN PROGRAM]I,TING Graphics programminp - Framc . Comnonenls working r.r,ith 2D shapes _ Lsing color.fonts. ?.nd images_ Basicsofevent handring evcnt handrers adaprer crasses aclions- mouse evenls _ A wr event
!;ff['.;;H:ll;'
"n
to Swing
- Model-vi"'i'"-c",t,"rr". al-G i,n".n'ii"*""" -
r,yout managemenr
-
2 marks:
l:'
Whal is fhe relalionship betnecn the Canvas class and lhe CraDhics class? A Can\as objecl provides access ro a Graphi*
2. Howlould
"Gi; ;;;il;#h";
you create a button with rounded edges? Ihere's 2 ways. The first thine is to knor,! that aJButton's edges are drawn by a Border. so you can 3 the Brr^n,e .oi.i.^--^-^-:.^,-_, . ffiTJa;,,1; and turn off the border o, a circle or rounded rectangle around any component and set the button,s border to it.
t":,,."1;j",*:":T1":fT{i",r,"r,.J*i i."*,T*,; y;;:;;;;;;" ;;;ffi ffi ffiIT#';
;;ffij ffiffi ,;rr"},:il
3.
What is the difference between the .Fotrt.and ,FontMetrics, class? The Font crass is used to render.gryphs,. the lou see on the screen. FontMet cs encapsulates informarion about a specific foni; ;.p""it" "rru.u"i"o 6;;p#;"df*' 1*ia',r, ascent,
"f,f,"
"haracters,
4.
What is the difference between the paintO and repaintO methods? The painr{ ) merhod supporrs painii"g ii" ""bj""i. ".r-r," , c*irl.,i.. painto lo be invoked b} the AW t painting tliread.
.
t
,"purnt
method is used ro cause
*1"I^::l_,f11*: r
usc a border Layout as rheir defautr tayour? ne wtndow, I ramc and Dialog classes use a border layout as
their default lavout-
6.
Differeoce between Swing and Awl? AWT are heavy-weiqht comnone)nets. Swings are lighGweight components. Hence swing works faster than AWT
,.
I*1lr,.
a layout manager and what are different types of layout managers availabte in java
is an objecl lhar is used to organize components in a container. The different r ,^..-...^ 1.lro.y,,T-ager rayours are avaitabte are ftowLayour. aora",uyour. c*Jiuyoui i.iiiuy-o*
#j
PREPARED
t
By: rrtrs.S.tqjini Assr.prof-CsE A rir.ii.Lalshmohor A.p_C.rE
c.iaergluyou,.
DEPARTMENT OF COMPUTTR SCTENCE AND ENGINEERING
8.
How are the elemetrts of dilferent layouts organized?( NOV/DEC,20I0l "#no., Flotelayoutt The elements of a Ftowlayour #" ,;'p-a left to right fashion. Bordetlqtout: The elements of a Borderlayor, u* "rg*i);"i, " ir," i"la"i" frr"nr,, s"r,r,, East and west) and lhe center ofa con tainer. cardlavout: "ffii*J"t The eremen-ts ofa cardr-uyori u." o*r."a. on rop ofthe orher. Iike a deck of cards Gridlalout:,r" oiu ciiaiiy"rii."?iq,i .rze and arc raid out using the "t"-"n* square ofa grid. GridBaglayout: The elements of a GridBaglayout are organized according to a grid. However, the elements are ofdifferent size and may occupy more than onJro* or ofthe grid. In addition, the rorrs and columns may have different sizes. "olumn The default Layout Man"ge. oipJn"r is Frowlayout. ""Ji,"r"r'..i "r"*es 9, Whywould you.use Sw-ingUtilties.invokeAndWait or SwingUtilities.invokel,ater? I wanl to updare a Swine componenl but I.m nol in a c;llba;k.-l;'i wanr the u.pdare ro happen immediately (perhaps for a progriss bar component) then |d use invokeAndwarr. rf r don.r care uhen rhe update occurs. l'd use invokeLater. 10.^What is the differetrce between scrollbar and scrollpane? A Scrollbar is_a component, but not a container wh"G.l".orrpur" is a conatiner and handres its own events and perform its own scrolling.
l
I WhJioIl't the JVM terminate when The Awr event dispatcher thread is not a thejVM.'--..-.-.lv!lliuJ!\^Pt'Llll'/L'
,j:-Yll-,1.
I
close
da..",
all the applicatioh windows?
*J. i;;;;:;;;;ii;il
-**
;",
system.exit to rerminate
O, controts and what are differenr types of controts in AW?.? ( onrors are components that allow a user to intemcl *i*, yor, tn" eWt suppons rhe following rypes ofconrrors: Labers. prrsh Buttons. "ppfi"uiion check s"*.. crii." liri..' r-ists, scrorbars. and rext Components. These controls are subclasses ofCoapo""ni,
*i
13. What is the difference between a Choice and a List? A^Cfoice is displayed in a compact form that requires you to pull it down to see the list ofavailable choices. Only one item may be selected from a-Choice, A List ,,", O'" ,.ch a way that several List items are visible. A List suppo.ts the selection ofone or more Li.t it"rn..
,
l,*rr"i ,
What is the purpose ofthe enabteEv€nts0 method? The enabreEventso method is used to enabre an event for a particular object. Normally,an event is enabled when a listener is added to an object for a particular ih" method is used by objects that handle events by oveniding their "r"n,. "nuut"ru"nts0 eventdispatch methods 14,
15. What is the difference betn een the File aDd RandomAccessFile classes? The File crass encapsurates the files and directoriehf the locar fire system. The RandomAccessFire class provides the methods needed to directly access data contained i, n".
"",
PREPARED
p"i"i"
By: rrt.s.S.Rojini Asst-prof_CsE & rrlr.r,i.Lakshmanon A.P,CSE
'l I
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 16. What is the lifecycle ofan applet? inito method - Can be called when an applet is first loaded starto meihod - Can be called each time an applet is started. painto method - Can be called when the applet is minimized or maximized. stopO method - Can be used when the browser moves
offthe applet's page.
destroy0 method - Can be called when the browser is finished with the applet.
17. What is the differencc between a Menultem and a CheckboxMenultem? The CheckboxMenultem class extends the Menultem class to support a menu item that may be checked or unchecked. 18.
What class is the top ofthe AWT event hierarchy? The java.aM.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
What is source and listener? source : A source is an object that generates an event. This occurs when the intemal state of that object 19.
changes in some way. /r'srere,, r A listener is an object that is notified when an event occurs. It has two major re4uiremerts. First, it must have been registered with one or more sourc€s to r@eive nolilications about specific types of events. Second, it must implement methods to receive and process these notifications.
20. Explain how to render an HTML page using only Swing. IJse a JEditorPane or JTextPane and set ir with an HTMLEditorKit, then load the text into the pane. 21.
llow would you detect a keypress iD a JcomboBox?
This is a trick. most people would say 'add a KeyListener to the JcomboBox' - but the right aNwer is 'add a KeyListener to the JcomboBox's editor component.' 22. What an I/O
filter?
An l/O filter is an object that rcads from one strcam and writes to another, usually altering the data in some way as it is passed from one srearn to another.
I create my own GUI components? Cr-rstorn graphical components can be created by producing class that inhe ts from java.aM.Canvas. Your component should ovenide the paint method,just like an applet does, to provide the gaphical features of the component. 23. How can
a
24. What is an eyent and what are the models av.ilable for evetrt handling? An event is an event object that describes a state ofchange in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two q?es of models for handling events and they are: a) event-inheritance model and b) event-delegation model
PREPARED
8y:
rrlrs.S.RoJlni Asst-Prof-CSE A rir.rl-Lokshmonon A.P-CSE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 25. Whal ls the
dilfererce between applicrtioDs rnd sppleh?
a)Application must be run on looal machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within ajava-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser, c)Application starts execution with its main method wh€i€ss applet starts execution with its init method. d)Application can run with or without graphical user interface whereas applet must run within a graphical user interface. 26. How are Frame Created in java? (NOV/DEC'2010 rnd NOV/DEC'20l1) A top level window is called a frame injava. The AWT library has a class Frame, The swing version of fram€ class is JFrame. The swing classes are placed in javax.swing.package Frame window:new FBme("This is the Frame's Title Bar").
. . o . .
16 1.
Marks:
Explain about Frrmes? (NOV/DEC'2010 ard NOV/DEC'2oI1)
Framcs Creatins Frames
.1.
A loo level window is called a frame in java.
.i.
The AWT library has a class Fmme.
.i.
The swing version offrame class is JFrame.
.4.
The swing classes are placed in javax.swing.package,
.t
Allswing components must
passes events such as mouse
4.
be configured fiom the event dispstch thread ,the thread
click and keystrokes to the user interface qomponents.
The following code is exeaut€ th€ statements in the event dispatch thread.
EventQueue. invokelater ( new Runableo
{ Public void run0 ( Statements
) PREPARED
By: rrlrs.s.Rojini Asst.Prof-CSE
A
r.rrt.t krhnonon A.P-csE
ofconfolthat
t"
I
1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING )); Proqmm to create the fmme importjavax.swing.*; import java.awt.*; public class Swing,Create_Frame { public static void main(String[] args){ JFrame frame = new JFrame("Frame in Java Swing");
frame.setSize(400, 400);
fiame.setvisible(true): frame.setDefaultCloseoperation(JFrarn€.EXIT_ON_CLOSE);
) ) output
Po,sitionins a Freme The methods used to position the frame are
java.awt.Componenl
l. setlocation (int x-int y) Moves th€ components to a new location. The x and y co-ordinates use the co-rdinates container-
2.void setsize(int width. int heieht)
PREPARED
,
By: ,rlrs.S.Rqiini Assr.Prof-CSE A lUr.l .kkshrlomr A.P-CSE
ofthe
DEPARTMENT OF COMPUTER SCIENCE AIID ENGINEERING resizes the
the specified width and height. getsizeo - to
ger the size.
int width. int hei Moves and resizes this component. The location ofthe top-left comer is given by x and y, and the new size is given by the widtl and height parameters. 4, void setTitle(Shine s) .gerTifl ter) gets
or
sets the
title properly to determi.e the text in the title bar ofthe frame.
5. void setvisible6oolean b).isVisibleo gets or sets the visible property
6.setResizable0. s€tResizable(boolean b) gets or sets the rcsizable property.
T.setlconlmaqe(lmaqe imaqe).setlconlmase0 gets or sets the iconimage property that derermines the icon for the frame.
8.void setTitle(Strin q newTitle) Change the
title in
a frame
window.
PREPAREO BY: ,r^rs.S.Rojini Asst.Prof-CSE
A r.rl.t
kshnonon A.P-C,SE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Figurc ?-5 illustratel the inheritauce cbaiu for the rrrarne cla:s, Figure 7.5. lnheritance hierarchy fof the JrraDe .nd Jpa-oel classes
PREPARED
By:
l
rs.S.Rqiini As3r-pIof-CSE & tVb-fl.L.kshmdrdn A.P-csE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Fr1ame
Pronertie.
l. Title
is one
ofthe properties
2. Location by platform is the another property
t
For gefting or setting the tittle , the methods eetTitle0 or settitle(Strins s) is used
.:. For getting
or
setting
the
locationbyplafform
,
.
isl,ocationBvplatformo oi
setlocatiodPlatform(boolean b) is used. In this property before the window display, the platform picks a suitable location for the display.
Frrme Size
,
Ifthe size for the frame is not given
means, default size
ofo
by o(zero) pixels
will
be assigned
for
the fiame.
*
For getting the screen size, the class ToolKit and the method setDefault,l oolKit() method are us€d.
.l
To get the screen size, dimension class is used to get the width &height ofscreen size.
.!. The code for this is
ToolKil K=ToolKir.gerDefaulrToolKir{ )l Dimensionsize--k_getScreensize0; int width=size.width; intheight=size.heighr;
setsizr(width/2, heighV2); //assigning half width and height of window to a frdme.
*
Ifthe ftame contains only
standard components such as buttons & textfilelds, the packo method
is called to set the frame size.
.:.
For maximizing a frame,
PREPAREO
gyr filrs.S.Rqiini Asst.p.of-CsE & r,lr.rrt.Laksh,nanon A.P-CSE
I I
l DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING frame.setExtendsState(FTame.MAXIMIZED_BOTH); is used.
*
rhe addilional melhods
. .
offrames are
toFronto shows this window on the top ofother windows. .
toBaako shows this window to the back ofthe stack windows.
2. How to Describe a Componenrs.
(NOV/DEC'20 )
COMPONENTS For displaying anlthing ie) a message or shapes another component is added or needed within ftame.
,.. .!
Normally fmmes are containers for all components.
.i
The root Dane , lavered pane .content Dane and qlass Dane are used to depict the container.
Fig:re
7-7. The inrernat
struc:l,r€ of r
.rEre
a.. {odir!a$
cq&{ t8llo -'".-,!Lsr
PREP^RED BY:
t
,rlrs.s.Rojini
sst.Prof-CSE
&
part3
r.rrt.lnl(shnonon A.P-Cs€
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERJNG For the addition ofcontainer within tame the .containe., class is usedContainer contentpane-tame. getcontentpaneo; Component
c=...........;
Contenl,Pane.add( c);
.!.
*
To add the components, the class Components is used ,and tlie method paintcomponent( ) is used to add the components such as images, text etc. lnstead ofJcomponent . Jpanel is also used to add the container.
Svnlax ofdrawstrine
drawstring(" string to be displayed.,,xposition,yposition) Program for frame aod panel display import javax.swing. *;
impot java.awt. *; class framepanel
{
public static void main{srring argsl])
{ JFrame f-new JFrame(..frame
& panel');
f.setsize=(400,400);
f.setvisible(true); f.setDefaultc loseop€ratiol(JFrame.Exit_ON_CLOSE); framecreation p=new flamecreationo;
f.add(p);
) PREPAREdBy: r,trr.S.Rqiini Asst.prof-CsE & llr.ltl.Lakshnon.n A.P-CSE
'I I
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING ) Class framerrbation extends JPanel
{ Public void paintcomponent(Craphics g)
{ g.drawSring("frame and panel creation",20,20);
) )
The advadtages ofcomponents are
*
Components are having preiefined classes and methods,
.:.
They can paint themselves.
{.
They can position and resize themselves.
t
They allow user interaction.
3. How to
yorking with 2D Shapes. (NOV/DEC'20f0)
Workins with Shaoes
*
Graphics class had methods to draw lines. rectanqles. ellipses and so on.
.1. Java 2D library implements
a
powerful set ofgaphical opemtions.
.:.
The package "geom" is used for graphical shape applications. It is Iocated in the
.:.
2D shapes are lines , ellipses and quadrilaterals.
'a\,t'
package.
-for the
.
Drawing ofshapes
PRE?ARED
t
8y: r,lrs.S.Rolini Asst.Prof-CSE'l i&.ll.Lokshnonon
A.P-CSE
11
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Painting of inner shapes Painting of linear shapes
Filling ofcolors Transformations.
'
'geom'package can be used.
6
galhiggD
t
This class uses floating point oo-orinates for the calculation. Because it
is the class used for &swing applications.
will for
rhe drawing
of
shapes.
i
The classes used are
Point2D, Line2D,Rectangle2D, Ellipse2D. -parent class
Rectangle2D
Rectangle2D.Float inrrerited class
Rectangle2D.Double
tfm
7',. 2D
]
6L!tll. rLn..
R6ctangle2D
Rectangle2D .Float
t PREPARED
Redangh2D -
DoLhle
,.trs.5.Rajini Asst.Prof -CSE & ilf.r{.Lolshnanott A.P-CSE
12
DtrPARTMENT OF COMPUTTR SCIENCE A}[D ENGINEERING Fig.,e 7-10. Relallo.shlps betwe.n the 3haPr
c'-.'.6
13
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING f.setsiz€(400y'00);
f,setvisible(true); f.setDefaultcloseoperation(JFrame.Exit_ON_CLOSE); com c=new como;
f.add(c );
) ) class com extends Jcomponent
Public void paintComponent(Graphics g)
{ Graphics2D G
gl
=(Graphics2D)g; // objecr creation
l.setPaint(Color.PlNK);
C I.drawstring("2Dshapes",
Point2D
p 1=ne\tr
I
// assigning color to
shapes.
00. I 00);
Point2D.Double( l00,l0O);
Point2D p2=new Point2D.Doubte(200,200); Line2D p2=ew Line2D.Double(0,0,100,100);
gl.draw(ll);
// dmwing of line I I
Line2D l2=ew Line2D.Double(pl,p2);
gl.draw(I2);
// drawing ofline l2
Rectangle2D r:new Rectangle2D.Double( I 00, I 00,200, I 50);
tnEPARtD By: i^rs.s-Rqiihi Asst.prof -CSE 6 rrlr-rrt.Lokshhanai A.P-CSE
74
,l l
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERJNG
gl.draw(r); Rectangle2D
//// dtawing ofrectangle using double values
rl:new Rectangle2D.Float(0.0f,0.0f, 100.0i1 00.00;
gl.draw(rl);
// drawing of rectangle using float values
Ellipse2D e1=new Ellipse2D.Double.(0,1 0,100,20); gI
.draw(rl );
// drawing of rectangle using float values.
Ellipse2D el =new EIlipse2D.Double( 0,10,1 00,20);
gl.graw(el); Ellipse2D e2=new Ellipse2D.Folat( I 00.0f, I 00.0i I 000.0f. I 000.00;
gl.draw(e2);
//ellipse drawing using float values.
) ) The sYntax of methods used are
l.
Point2D.Double(double x,double y);
2.
Line2D.Double(double startxdouble starty, double endxdouble endy);
3.
Line2D.Doublel Point2D stan.Poin12D end):
4.
Rectangle2D.Double(double x,double y,double w,double h);
5.
Rectangle2D.Float(floar x, float y,float w,float h);
6.
Ellipse2D.Double(double xdouble ydouble w,double h);
7.
draw(graphics object)
The additional methods are
*
double setcenterxo.double eetcenterYo
PREPARED
i
By: rrlrs.S.RoJini Assf .ft'of-CSE A rlr.r't.Lol6hndnon A.P-CSE
15
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING for getting center
{.
ofx
and y axes.
doublc cetMirx0. double setMinYo
For getting minimum values
+
and y axes.
double qetMaxxo . double ceMaxYo
For getting maximum values
.:.
ofx
ofx
and y axes.
double eetwidtho. double qetHeiqhro
for getting the width and height ofthe enclosing rectangle.
*
double qetx0. double eetY0
for getting x and y co-orinates ofthe top . left comer ofenclosing rectangle.
4. Describe how to use Colors
,
Fotrts rtrd Imrges thst (NOV/DEC'2010 and NOV/DEC'20I1)
tu 2D Shap€s and method! involved
$!s!s!e!c
.,
setPaint0 method is used to select a color that is used for all subs€quent drawing operation,
The ryntrx is s€tPaint(Color,RED);// class Color, RED- color to be dr8wn.
€.
It
+
lt has 13 standard colors, They are
is offered by the packages java,aM,
Black,Blue,lyan , Dark-$ay, gray,ge€n,light-gray,magenta, orange,pinkred,white,yellow.
t
The custom color Can be created by using color object, By the red, green and blue components.
The values should be in the range ofO t0 255.
in
i
A
,l.'
t'Ldst6@'r
A'P-CsE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
.:.
The systemcolors are
Tabl. 7-2. Systerfl co:o6 lackground cdor oi desiilop lackgrolnd cdot icr captEns cxt color ftrr caF ons ordea colcr to_ caption text
::.:::v:::-t::::,,-.-,,.-
':ric:iYeai:;:::1:ex: :.ac::iye:e:_-i.nts.: r: l.:
a(kgaound cdor for inactive caplions ei color flr inactrve caplions
orjer colcr fo' inecli!€ calticns aakground for wrndows Color
fe
oa
windorv border ,.ame
c{rlor itside w{ld!,ws
Background for menus Iexl {_Jr$a f)r menus
exr:ra:tiqei:*t
i'.=::igl:.,':::::: tEtrat1.t:righ:i9::: .nt!!ftj.qrli.qht ..:r.i!,r1shaln$ er..r.1lk-S:dd.'r'
3ackqround cdor lD, tex: ed cglor for texl ext color frr l€cliye controls
a.kgrrund cdor fDr highl,ghled iext fext coro, fo{ hghlqhled len 3ackg.otind cdor rcr sntrds felt color f.. .rnlrn c rqhl hiqhlAht coio. fo{ contro:s {ighiigltt colo. for controis ihedoy, coo. ilr crntols )a* sl"adcw colo.tor conl.ols ackground cdor lor scrollbars ackground color fDr +ol+relp text ext cdor frr spot+relp tPxt
Fonts
.i
For the specific font, the font name should be given.
*
The font face name is composed
ofa font family
name, style and point siz€.
*
To find the available fonts in a particular computer, 9l!!yqi]eh!9Eqd!IeBilyNq!!9s_]C method in 'GmphicsEnvironment' class is used. This method retums an array ofstrings that contai[s the names ofall available fonts.
PREPARED
i
By: i^rs.s.Rqiini Asst.Prof-CsE & ilr.il.L.kshmdhon A.P-CSE
r7
DEPARTMENT OF' COMPI]TER SCIENCE AND ENGINEERING
{.
For the local fonts , the method getlocalcraphicsEnvironment0 method is used.
a
The AWT defines five logical font names.
Sanserif
Serif Monospaced
Dialog Dialoglnput There names are mapped to fonts that exist on the client machine.
To apply a particular font, the object ofthe
.&4
, class should be created.
The syntax is Font objecFnew Font(,hame of font,,,style, pointsize);
.1.
The example is
Font Fnew Font(,,Sanserif,,Font.BOLD,l4);
.t
The style includes
Font.PLAIN,Foht.BOLD,Font.ITALIC. The method createFont0 is used to create the font from a file (or)url. The method deriveFonto is used to get the font ofthe desired size. The s)ntax
ofthis method is
derivefont( int sltle ); deriveFont(fl oat size);
.
deriyeFont(int style float size);
PREPARED
ay: ,{rs.S.Rqjini Assi.prcf-CsE a l,lr.tt^.Lokshmomn A.p-CsE
I
i
DFPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
.:.
To get the font characteristics of a screen device , the method getFontReadercontext0 method of Graphics2D class is used. It returns the object ofthe FontReadercontext class.
.1.
The code is
FontReadercontext c=g2.getFontReadercontext0; Rectangle2D b=f.getStringBounds(message,c);
getstrjngBounds -this method retums a rectangle that enclose the string. Basic tvDesettinq terms
rekr
Fig.rr. 7,13. Type.odng t.rrn3 illu.tral.d
bssalns
-I+
h.'qi
*** lI
.i.
Baseline is the imaginary line.
t
The ascent is the distance from the baseline to the top ofascender which is the upper portion.
{. .!.
The descent is the distance from the baseline to a dglg9ld9lwhich is the lower portion. lg3dilg is the space between the descent ofone line and the ascent ofthe nextline. The height of a font is the distance between successive baselines, which is
,
same as descent
+leading+ascen!.
'!'
To know the descent or leading , the method ,eetl"ineMetricso, method of the Font class is used.This retums the object ofthe 'LineMetrics, class.
.:.
-Eadhg
The methods in this class are
getAscent0- getting the font ascent.
PREPARED
t
By: ilrs.S.Rqi;ni Asst.Prof-CSE & rrlr.r{.Lqt hhonon A.P-CS€
19
DDPARTMENT OF COMPUTER SCIENCE AND ENGINEERING getDesc€nt0-getting the font descent. Getleading()-for getting leading space.
getHeight(>for getting the height ofthe font.
t
The additioDal methods are
getFontName0- getting the font name. gerFamilyo- getting the font family. getName0-gefting rhe logical name. getFonto,setFont(Font font) getting and setting the cunent font. gelFontMetrics()- getting the font metrics ofgiven font.
Displayins Imoses
.:. .:.
The images such as photographs or complex images can be displayed within a liame. One images are stored in load files, they can be displayed within a application.
.1. The filename is assigned using Image class &imagelO class is used to load the image.
*
The code lbr this is
String
file="':
Image i=lmagelO.read(new File(fi le)); The URL name is given instead
offiien4e.
The code for this is
String ull=" "; Image i=lmagelO.read(new URL(url));
PREPAREDBy: ,s-s.RoJini As+.prof-CSE & l{r.r,t.Ldkshmohon
A.P_CSE
zo
I
I DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
.:.
The read method throws an IOexception
*
The drawlmage() method is used to load the image. This is in the paintcomponet0 method.
.:.
The syntax for this method is
ifthe image
is not available
drawlmage(lmage img, int x, int y, Imageobserver observer)
x,y
co-ordinates
obseaver- the object ofrendering process.
Usingthis, the image can be Ioaded within the window. 5, Explain about Event
Handling?
Basiqs of Event I{andlitrg
.i.
For the implementation ofuser intedaces, event handling is main thing.
.a. The operating environment monito$ events such as keystrokes (or) mouse clicks.
.:.
The operating environment repots these events to the programs that ale running.
.:.
The coding for the response olevenls are called as'Event Procedures'.
{ ft
.a. The components which are used to pass the events are called as 'Event Sourceh'. (Ex) Buttons. scrollbars
etc. a\
t
The objects that are listening the state ofthe components
.:.
Any object can be an event listener. this is called
i.
The information about the event is captured in 'eventobject'. For the 'Ey9!1!!fhi!!I-9b!g , some
are 'Ey@LIi!l!9!9!].
as event deleqation
)
model.
subclasses are derived like ActionEvent and WindowEvent.
.1. Because different event sources produce different t,?es of events. For example a bg$9!-gg! send ActionEvent object. A window can send WindowEvent obiect.
PREPARED
Sy: rr^rs.s-Rdjini Asst.Prof -CsE
A
r.rrl.Lokhnionon A.P-CSE
27
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Flrurc 8-1. Event .otificarion
The steps for the evelt haDdlitrg are
l- A listener object is an instance of a class that implements a special interface interface.
"u,,"d
u ,io"r".
2. An event source is an object that can register objects and send them event objects. 3. The event source sends out event objects to all registered listeners when that event occurs.
4. The listener object
will
then use the infomation in the event object to determine their reaction to the
event. PREPAREDTBy:
r.trs.s.pqjini Asst.prof -CSE & rrlr.rrt.Lokshrnnon A.P-CSE
DEPARTMENT OF COMPIITER SCIENCE AND ENGINEERING
n
To implements the Actionlistener interfac€, the Listener class must have a method
called
actionPerformed0that receiver an ActionEvent object as a parameter.
The program for the action event is the example program for performing login operation.lf the usemame
&
password are correct means, the user gets the welcome screen.
Ifnot the user
gets the
dialog box ofspecifying that they are incorect.
5.
Explaitr about Swing-lUodel-Cortroller DesigD? (NOV/DEC'2010 and NOV/DEC,20l1)
Swins-Model-Controller Desisn Design patterni this is concemed with the components of a subsystem with their relationships and collaboration with each other. these are elem€nts ofreusable object-o ented software.
MODEL: this is the data ofthe application, along with the business logic that defines how to change the data, This is the domain specific representation
access and
ofthe data. this represents the state and low level
behaviour ofthe component . this manages the state and conducts all transformations on that state.
view:This means ofpresenting the model,s data to the outside world.this could take the form ofa GUI. this manages the visual
disilay ofa GUI. this manages the visual display ofthe state represented by the model.
Controller: lt receives input and initiates by the model. response by making calls o. model objects. it interacts with the model. this accepts input ftom the user and instructs the model and view port to perform actions based on that inpul.
Model specilies the content such as the stale ofa button.
PREPARED BY:
t
ilrs.S.Rojini Assi.Prof -CSE & rrlr.rr^-Lokhmonon A.P-CSE
23
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
.:.
View specifies the visual appearance (color, size etc)
.:.
Controller specifies the behaviour ofcomponents.(eaction to events)
{.
Thrce separate classes are implemented. they are
l.
Model: sto.es the content
2.
View: displays the content
3.
Conholler: handles user input.
.:.
The model must implements methods to chalge the cont€nt and to discover what the content is.
.i.
The model can have multiple views.
.1. When the views
are
notified , they refresh thgmselves automatically.
.:.
The controller handles the user-input events such as mouse clicks and keystrokes.
.:.
Each user interface component has a wrapper class. Ex button-jbufton.
.:.
Mvc pattem is attractive for swing components
*
Models a.e easy to separate and each user interface component has a model class.
fvM
.
Anelvsis of Buttops
*
Buttons are the simplest user interface elements.
,
The model class implements an interfac€ whose flarnes ends in 'model' . So the interface is called 'buttonmodel'
a
.
Properties of'buttonmodel' interface are
value
DroDertiesName
actioncommand
action command associated rvith the button.
mnemonic
keyboard mnemonic
PREPARdt By: ,.trs.S.RoJini A$f-Prof-cSE & i^r.rl.L.otshnonon
A.P-csE
24
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
armed
true if the button was pressed & the mouse is still over the button.
enabled
true ifthe button is selectable_
pressed
true ifthe button was pressed but the mouse button hasn't yet been released.
rcllovq
true ifthe mouse is over the button.
selected true ifthe button has been toggled on. .:. This 'Buttonmodel' is the interface that can be used for buttons, togglebutsons,
check boxes radio
buttons,menu items,menus tec.
*
'Document' interface is used for the design oftext field , text area etc.
6.
ExplaiD about Layout?
.:. A layout is a set of rules that defines how graphical
component should be positioned in a cohtainer.
.:.
There are two ways to position a component.
.i.
The pre-defined layout can be used to position the component.
,
The co-ordinates can be given for positioning the components. But this is too hard.
{.
The Layoutmanager determines the position and sizes ofthe components in the codtainer.
*
Each container has a default layout manager ,but other layouts can also be set by the user.
.:. AWT offers a number
ofpredefined layouts to use.
FLOWLAYOUT
i
This is the default layout. It takes unlimited number of components.
.t
It
{.
It positions each component next to each other ina row.
uses the default size
The sv[tax is
PREPARED
t
ofeach component.
.
By: rlrs.s.RoJihi Asst.Prof-CSE & lrlr.rl.Lakshmdnoh A.P-CSE
25
DEPARTMENT OF COMPUTER SCIENCE AIID ENGII\IEERING Flowlayout{) (or) flowlayou(int align) BORDER LAYOUT
.:.
This divides the container into five regions.
t
East, west north, south, center.
.:.
The north
& south components
arc placed horizontally and the east
& west components
are placed
vertically.
.!
lt takes maximum 5 components only one per region.
.t
This acts as the default layout in a container.
,t
This will be looking like this
North West
Center
East
south
The svntax is
Borderl-ayout0
GRID LAYOU:
t
It
*
It ananges all components in rows and columns.
*
It resizes all components when the container is resized .
plac€s components in a grid of cells.
The syntax is
Cridlayout(int rows, int columns); SOPEISTICATED LAYOI'T MANAGEMENT
26
DEPARTMENT OF COMPUTER SCIENCE AND ENGINIEERING
.:.
additionally two layouls are used for the decorative purpose. they are
l.
Box layout
2.
Gridbag layout
BOX LAYOUT
*
It
.:.
It takes unlimited number of components.
places compolents either vertically or horizontally.
The svntar is
Boxlayout(axis) axis
- X-AXIS, Y-AXIS,LINE-AXIS & PAGE-AXIS.
GRIDBAG LAYOUT
{.
This places componenrs in a grid ofrows and columns.
i.
Here tfie rows
& columns
can have vadable sizEs.
.1. The adjacent cells can bejoined for the display oflarger components.
*
For the airangement
of
components the class .GridBagConskaints,
is us€d the
important
constraints are
l.
gridx
2.
gridy-.components
3.
gridwidth- components horizontal giid extend
4. g 5.
-
components horizontal grid origin.
vetical g
d origin,
dheight- components vertical gfid extend
weighu- specifies how to dislribuE extra horizontal space.
FnEPARED
t
By: ,tui.s.Rojini Asst.prof-csE &
iti:f
.klfhmdmr A.p-CsE
27
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
6.
weighty- specifies how to distribule extra vertical space.
The s)mtax is
GridBaglayouto;
7.
Explain about Swing Compotrents? (NOV/DEC,201I)
Swipe Compotrents
"$eE-
this is the static text. The base class
is
jl!g!!e.
The syntax for lhis is,
Jlabel lbl=new Jlabel(text of label);
71
Jlabel Ibl=new JLabel(texr. alignment); Jlabel
Ib I =new JLabel(icon):
Jlnbel
lb I =new JLabel(icon. alignment);
.:.
The alignment specifies the direction ofanangement (ie) RIGHT,LEFT (OR) CENTER.
.:.
The related methods are
String getTexto
gets/ sets the text ofthe label.
void setText(String text)
)
lcon getlcono
gets/sets the icon
void setlcon(lcon icon)
ofthe label.
)
'fexthorf h
LU [-.ra
A.s/
There are two types oftest inputs . they ale
.
TexrFierd
,- s,t\^ €
. r"**nu/1 X*IlvF'r PREPARE'b BY:
i
(r!rr lro-Fr: * A t h.^Ac.r6-ot: l*r'
(\-".ou q-'r.D rs.S.Rajihi Asst.Prof -CSE & rrtr.r{.L.kshmdnon A.P-CSE
28
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING TeItField
.:.
This can accept only one line oftext.
*
The base class is JTextField.-
Tho syntrx is
.,7
.|.
JTextField(int columns)
.:.
JTextField(String text,inL col]umns)
,/?
The related methods are
*
int getColums$/setcolumns(int cols)
gets/sets the number ofcolumns of text field.
* setTex(String)
I
gets/sets rhe lext in the text fileld.
t
getText()
.:.
Stsing
,,
setEditableo for making the components to edit.
.!
setHorizontalAlignment(align)
l.
Multiple lines oftext can be added into the textarea.
l.
The base class is JTextArea.
I
)
-
for arranging the alignment.
.1. The sy,ntax is JTextArea(ro\rys,columns) The related methods.are
gertext()
+
String
t
void setText(String text)
PREPARED
!
I
I
gerVsets the rext in rextarea
)
l t
gy: rlrs-S.Rqiini Asst.Pro+CsE & rlr.r,l.Ldkshnanon
A.P-CSE
29
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING void append(Stxing text)
inserting the text into the textarea.
*
void insert(String text, int position)
.!.
void setEditable(booD to make the editability.
*
setBordero for setting the borde..
."*o.anaa
./
*
This is a special kind oftext fileld.
.:.
The characters entered by the user are not actually displayed, The echo characters are displayed instead of actual cha.acters.
.i.
The base class is JPasswordField.
The syDtax is JPasswordField(String text,int columns) The related methods are
.
void setEchoCha(char echo)
.
sets the echochamcter fbr the password
field.
/ScrollPanes
*
The scrollbars can be insened to the components.
.i.
The baseclass is JScrollPane.
.!.
The syntax is
JscrollPane(Component c)
.!.
The scroll pane is added with the specified component.
FnEPAeEb By: r{rs.S.Rojini Asst.P.of -CSE A rrlr.r{.Latsh6amn A.P-CSE
30
l,
DEPARTMENT OF COMPUTER SCIENCE AND ENGIIIEERING Buatons
.l
The base class is JButton
.:.
The syntax is
JButton(Slring); JButton(image); JButton(text, image)
.:.
The related methods are
-
setEnabledQ
for setting enabling / disabling
Choice Comoonents
1.
Checkboxes
2.
Radio buttons
3.
Com'boboxes.
Ch*kboxes,
.
zfl
/7
.:.
The check is used to get the ioput
J.
Checkboxes have the labels automatically.
of,yes'or.no,
tPa
.1. The user usually checks the box by checking inside it and tums offthe check mask by clicking inside the box again. To toggle the check mark, the user can also prcss the spacebar when the focus is in the checkbox.
.i.
The base class is JCheckBox
*
The syatax is
JCheckBox(String label); JCheckBox(String label,lcon icon); PREPLRED BV:
i
r,ts.5.Rqiini Asst.PFof-CSE & r r.rrl.Lotshhonon A.P-CSE
t1
DEPARTMENT OF' COMPUTER SCIENCE AND ENGINEERING JcheckBox(String label, boolean state);
*
The related methods are
Boolean isselected0
I
gets/ sets the selection state oIcheckbox.
J
void setselected(boolean state) Radio Buttons
*
ln cheokboxes ,the users can check either , both or neither ofthe checkboxes. But in many cases the
input is single thing
.
in thi's situated , it can checkbox is checked means, other should
be
automatically unchecked.
.!.
For this , a group of buttons are used, these are called as .,Radiobufton$oup,, and the individual buttons are called as "Radio buttons"-
,
The base classes ate Buttoncroup
& JRadioButton.
The syntax is
b
r-"Jt o
oLo./,P
JRadioButton(String text, Icon icon);
JRadioBufton(Sting tect,boolean state); The related methods are isSelectedo setselected(boolean f)
sefting/getting the seleotion state.
)
Combo Box
t
For the list of choices display , the combo box is effective . in this list of items , one item can be selected by the user.
.:.
It combines the flexibility ofa texr field With a set ofpredefined choices. The base class is JComboBox,
PREPAiEb Sy:
t{rs.S.Rojid Asst.Prof-CSE & rlr.rrl.Lotshhqnor A.P-CSE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
The related hethods are boolean isEditable0
gets/ sets the editable Eoperty of combo box.
void setEditable(boolean b) void addltem(object
item)
- add an item to the lisr.
void insertltemAt(obj ect item,int index) inserts the item to the item list at the specified index.
void removeltem(object item)
-
removes an item from the item list.
void removeltemAt(int index) remove the item at an index.
void removeAllltems0
,
object getselectedltem0
removes all items in the item list.
-
rgturns the currently selected items.
Sliders
.i.
Combo box provides a discrete set ofvalues.
i
Slider offers a choice from a continuous set ofvalues.
t
The base class isjslider.
.:.
The syntax is
.
JSlider(int'min, int max, int intialvalue);
.
Jslider(int min, int max);
.
lslider(orientation , min.max, initial values)
{.
The ticks can be shown with sliders. the methods to set the ticks are
LotJi
PREPARED
i
By: i^rs.S.Rojini Assf.ft\of-Cs€ & /tlr.r{.Lokshnomr A.P-CSE
33
.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
.
setMajorTickspacing(20);
.
seMinorTickspacing(5):
.1. The slider is decored with large tick marks.At every 20 units and small tick marks ateverv 5 units.
*
To show lhe tick marks. The merhod-
o
Metrus
setPaintTicks(true) should be called.
s-l
h^a-''
A menu bar on the top of the window contains the names of the pull down name opens the menu containing menu items & sun merus.
+ .i. .:.
*
menus. Clicking on a
For creating menu First the menu ba.is created. The base class isjmenubar. This menu bar is added with the frame using method, setjmenubao. For each menu, menu object should be created. The syrtax for this is, jmenu(String texr) For adding menu items , sepiuators the coresponding methods are used . the syntax is
JMenultem add(Jmenultem item): JMenultem add(Stdng label) void addsepartoro
-
to add separators
& among menu items.
JMenultem insen(JMenultem .int index): add a menu item at the specified index.
void remove(int index), void remove(JMenultem item); removes a specific item from the menu.
1.(,.....^-
crjrL e.t
X,-,...^.
for setting items to the items , the syntax is pREpAREDtr,By:
,rbs.s.Rojini
*st. prof-csE a ,r,lr. il. tnkshnonon
A.P-CSE
34
i: )
DEPARTMENT OF COMPUTER SCIENCE AIID ENGINEERING JMenultem(String text, Icon icon) CheckBox
.i.
& radioButtond Meuu items
These items display a check box or radio button next to the name. When the user selects the menu item. The item automatically toggles between checked
.i.
& unchecked.
The base classes are
JCheckBoxMenultem & JRadioButtonlrem The synt.x is JCheckBoxMenultem(String text); JcheckBoxMenultem(String text, boolean state); JRadioButtonltem(Shing text); JRadioButtonltem(String text, boolean state); The other related methods are boolean isselected0
getvsets the selection state ofthe item
void setselected(boolean state)
)
DOlr-uD menus
.1. This is not attached to a menu bar but that float somewhere.
{.
The base class for creating popup menu is JpopuMenu.
.:.
The 'JMenultem' class is used to add the menu with the pop-up menu.
l.
For displaying pop-up menu in the panicular component
*
The syntax
ofthis
& location
.
the method showo is used .
is
void sw(component c, int x, int y);
PREPARED
t
By: rtus.S.Rqjini Asst.Prof-CsE a,llf.ltl.l.atshnlonon A.p-CsE
35
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING The other related methods are
t
getcomponentPopuprr4enu0
]
gets/sets the pop-up menu for a particular component.
setcomponentPopupMenu0
t
Boolear getloheritsPopupMenu0
the inherits p.operry.
Void setlnheritsPopupMenu(boolean b)
)gets/sets
'!'
Keyboard mnemonics are keyboard shortcuts for the menu items. These are used to 3elect a sub menu or menu item from the currently open menu.
n
Accelerators are keyboard shortcuts to select menu items without opening a menu.
n
The methods used to set the mnemonic are.
JMenullem(String text.int mnemonic) void seMnemonic(int mnemonic)
*
The methods used to set the acc€lerator are
void setAcc€lerator(Keystroke K)
*
For enabling (or) disabling the menu item the method
void setEnabled(boolean b) is used.
Toolbars and ToolTios
,
A toolbar is a buttonbar that gives quick access to the most commonly used commands in
.:.
The toolbar can be moved anywhere.
Pf,EPAREPBy: rlil.s.s.Rojini Asst.prof -CsE
a r,lr.rrt.Ldtshnoon
A.p_CsE
a
progmm.
DEPARTMENT OF COMPUTER SCIENCE A}ID ENGIIYEERING
{.
The base class is JToolBar
a
The syntax is
l.'
.
JToolbar(St ng titlestring)
.
JToolBar(int orientation)
.
JToolB&r(String titlestring,int orientstion)
Tooltip is the text that is displayed inside
a
colored rectangle.the tooltip is ,
Void setToolTipText(String text)
*
The tooltip is displayed when the mouse moves over the component.
BORDERS
*
Swing provides a set ofuseful Borders.
*
The borders can be placed around a panel or a.ound other user interlac€ elements such as radiobuttons.
.:.
'BorderFactory' static mathod is usei to create a border.
*
The types ofborders are
l.
Tittle Border
2,
Compound Border
3.
EmptyBordcr
4.
LineBorder
5.
EtchedBorder
6.
Raised BevelBorder
7-
LoweredBevelBorder
PREPARED
o !J+..r
By: r,trs-s.Rqiihi Ast.Prof -6SE A lit.tt^.L.kshrldndn A.P-CSE
6 &.9
,
,7
DtrPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
8. Sv
MatteBorders
ax for Tittle Border
createTitledBorde(String title) createTitledBorder(Border border) createTitledBorder{Border border,String title) crcateTitledBorder(Border border ,St ng title,inl justification,int position)
cr%teTitledBorde(Border border ,String title,int justification,int position,Font font) createTitledBoder(Border border ,String title,int justification,int positiod, Font font,Color color) Svntar for CompoundBorder createcompoundBorder(Border outsid€border,Border insideborder) Svtrtax for EmptvBorder
createEmptyBo.de() createEmptyBorde(int top,int left,int bottom,int.ight)
Svnttr for LipeBorder createlineBorder(Colo. color) createlineBorde(Color color,int thi'ckness) SY[tax for EtchedBorder createEtchedBordeo createEtchcdBorder( Color highlight, Color shadow)
oeateEtchedBorder(int typ€) createEtchedBorder(int type, Color highlight, Color shadow)
PREPAREb
By: ,lE.S.Rqiini Asst.Prof-CSE A ,lr.rrt.L6kshnon@
A.P-C5E
38
,] 1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING SYntax for BevelBorder
createBevelBorder(int type) createBevelBorder(int type,Color highlight Colo. shadow) createloweredBevelBordero qeateRaisedBevelBordero
A!!ax for M4tteBgldgI! createMatteBorde(int top,int left,int bottom,int right,Color color) creatematteBorde(int top,int left,int boftom,int right,lcon icon) Sytrtax for SoftBeyelBorder Soft BevelBorde(int
t,?e)
SoftBevelBorder(int type, Color highlight,Color shadow) The method used to the set the borde. is
setBorder(Border border).
Dialos Bores Dialog boxes are used to get information fiom the user orprovide information to the user. There are 2 types.
Modal alld tuodeless dialog boxes-
l.Modal : without closing the modal box, the user can,t work with other windows. e.g Save dialog.
2.Modeless: the user can work with multiple windows by having a modeless diadlog. e.g search, search
PREPAR€D
t
& replace dialog.
Byi t{rs.S.Rqlini Asst.Prof-CSE a rir.i^.t otshmonon A.p-CSE
39
DEPARTMENT OT' COMPUTER SCIENCE AND ENGINEERING Swing has a set of simple ready_ made dialogs . the base class is JOptionpane. The methods used to create dialogs are The Joptionpane has four static methods showMessageDialog -Show a message and wait for the user to click OK.
showConfirmDialog -Show a message and get a confi.mation (like OK/Cancel).
showoptionDialog- Show a message and get a user option from a set ofoptions. showlnputDialog -Show a message and get one line of user input. The dialog has the following components; . An icon;
. A message; . One o. morc option buttons.
*
showMessageDialog(Component
.:.
parent,Object message,String title,int messagetype)
showconfirmDialog(component parent Object message,string
title,int
optiontype,int
title,int
optiontype,int
messagetyf,e)
t
showoptionDialog(Component parent,Object message,String messaget)?e,lcon icon,Object[] options, Object default)
PREPAREq,BY:
r,r.s.RaJini Asst.Prof-CSE &
rrtr. rrt.Lckshhonon A.P-CSE
40
DEPARTMENT OF COMPUTER SCTENCE AND ENGINEERING Utriversity Questiotrs: 2 MARKS:
1.
Hoiv are the elements ofdifferent layoufs organizid?( NOV/DEC'2010) Refer P.ge" No: 2
2.
How are Frame Created in java? (NOV/DEC'2010 and NOV/DEC'2011) Refer Page. No: 4
16
l
MARKS: Explain about Frames? (NOV/DEC'2010 and NOV/DEC'20I1) Refer Page. No: 4
2.
How to Describe Colnponenrs. (NOV/DEC,20II) Refer Page. No: 9
3.
Descrilre how to use Colors, Fonts atrd Imag€s in 2D Shrpes and methods involved in that.(NOV/DEC'2010 and NOV/DEC,20l1)
Refer Page. No: 16
4.
'
Explair about Swirg-Model-Controflg!ry8!0lov/DEc'2010 &trd NOV/DEC'2011) Refer Page. No: 23
5.
sr!i!gQlM!!:
Explain about Refer Page. No: 28
-rr\*\s)!4
\g_---.'-
Pq.d b r. .?.
s.
Pdiai - \S----)
M.hl.sl-ano"
!fi'lOv/DEC'20r 1)
H 'd.',FJ iloPlca€
an-J td \i \, Pinu9l \ t. r,
- hU.-
PRPARED By: i^rs.S.Rqiini Assl.Prof-CSE & t$-r{.Lokshnonor A.P-CSE
t
j,i
41