Tải bản đầy đủ - 0 (trang)
Chapter 22. GUI Components: Part 2

Chapter 22. GUI Components: Part 2

Tải bản đầy đủ - 0trang

Chapter22.GUIComponents:Part2

Anactorenteringthroughthedoor,you'vegot

nothing.Butifheentersthroughthewindow,

you'vegotasituation.

BillyWilder

...theforceofeventswakesslumberoustalents.

EdwardHoagland

YouandIwouldseemoreinterestingphotography

iftheywouldstopworrying,andinstead,apply

horsesensetotheproblemofrecordingthelookand

feeloftheirownera.

JessieTarboxBeals

OBJECTIVES

Inthischapteryouwilllearn:

Tocreateandmanipulatesliders,menus,pop-upmenus

andwindows.

Tochangethelook-and-feelofaGUI,usingSwing's

pluggablelook-and-feel.

Tocreateamultiple-documentinterfacewithJDesktopPane

andJInternalFrame.

Touseadditionallayoutmanagers.



[Page1006]

Outline

22.1Introduction

22.2JSlider

22.3Windows:AdditionalNotes

22.4UsingMenuswithFrames

22.5JPopupMenu

22.6PluggableLook-and-Feel

22.7JDesktopPaneandJInternalFrame

22.8JTabbedPane

22.9LayoutManagers:BoxLayoutandGridBagLayout

22.10Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page1006(continued)]



22.1.Introduction

Inthischapter,wecontinueourstudyofGUIs.Wediscuss

additionalcomponentsandlayoutmanagersandlaythe

groundworkforbuildingmorecomplexGUIs.

Webeginourdiscussionwithmenusthatenabletheuserto

effectivelyperformtasksintheprogram.Thelook-and-feelofa

SwingGUIcanbeuniformacrossallplatformsonwhichaJava

programexecutes,ortheGUIcanbecustomizedbyusing

Swing'spluggablelook-and-feel(PLAF).Weprovidean

examplethatillustrateshowtochangebetweenSwing'sdefault

metallook-and-feel(whichlooksandbehavesthesameacross

platforms),alook-and-feelthatsimulatesMotif(apopular

UNIXlook-and-feel)andonethatsimulatesMicrosoft'sWindows

look-and-feel.

Manyoftoday'sapplicationsuseamultiple-documentinterface

(MDI)amainwindow(oftencalledtheparentwindow)

containingotherwindows(oftencalledchildwindows)to

manageseveralopendocumentsinparallel.Forexample,many

e-mailprogramsallowyoutohaveseverale-mailwindowsopen

atthesametimesothatyoucancomposeorreadmultipleemailmessages.WedemonstrateSwing'sclassesforcreating

multiple-documentinterfaces.Thechapterfinisheswithaseries

ofexamplesdiscussingadditionallayoutmanagersfor

organizinggraphicaluserinterfaces.

Swingisalargeandcomplextopic.TherearemanymoreGUI

componentsandcapabilitiesthancanbepresentedhere.

SeveralmoreSwingGUIcomponentsareintroducedinthe

remainingchaptersofthisbookastheyareneeded.Ourbook

AdvancedJava2PlatformHowtoProgramdiscussesother,

moreadvancedSwingcomponentsandcapabilities.







[Page1006(continued)]



22.2.JSlider

JSlidersenabletheusertoselectfromarangeofinteger

values.ClassJSliderinheritsfromJComponent.Figure22.1shows

ahorizontalJSliderwithtickmarksandthethumbthatallows

theusertoselectavalue.JSliderscanbecustomizedtodisplay

majortickmarks,minortickmarksandlabelsforthetick

marks.Theyalsosupportsnap-toticks,whichcausethe

thumbtosnaptotheclosesttickmarkwhenitispositioned

betweentwotickmarks.



[Page1007]

Figure22.1.JSlidercomponentwithhorizontal

orientation.



MostSwingGUIcomponentssupportuserinteractionsthrough

themouseandthekeyboard.Forexample,ifaJSliderhasthe

focus(i.e.,itisthecurrentlyselectedGUIcomponentinthe

userinterface),theleftarrowkeyandrightarrowkeycausethe

thumboftheJSlidertodecreaseorincreaseby1,respectively.

Thedownarrowkeyanduparrowkeyalsocausethethumbof

theJSlidertodecreaseorincreaseby1tick,respectively.The

PgDn(pagedown)keyandPgUp(pageup)keycausethe

thumboftheJSlidertodecreaseorincreasebyblock

incrementsofone-tenthoftherangeofvalues,respectively.

TheHomekeymovesthethumbtotheminimumvalueofthe

JSlider,andtheEndkeymovesthethumbtothemaximum



valueoftheJSlider.

JSlidershaveeitherahorizontalorientationoravertical



orientation.ForahorizontalJSlider,theminimumvalueisatthe

leftendoftheJSliderandthemaximumisattherightend.For

averticalJSlider,theminimumvalueisatthebottomandthe

maximumisatthetop.Theminimumandmaximumvalue

positionsonaJSlidercanbereversedbyinvokingJSlider

methodsetInvertedwithbooleanargumenttrue.Therelative

positionofthethumbindicatesthecurrentvalueoftheJSlider.

TheprograminFig.22.2,Fig.22.3andFig.22.4allowsthe

usertosizeacircledrawnonasubclassofJPanelcalledOvalPanel

(Fig.22.2).Theuserspecifiesthediameterofthecirclewitha

horizontalJSlider.ClassOvalPanelisasubclassofJPanelthat

knowshowtodrawacircleonitself,usingitsowninstance

variablediametertodeterminethediameterofthecirclethe

diameterisusedasthewidthandheightoftheboundingboxin

whichthecircleisdisplayed.Thediametervalueissetwhenthe

userinteractswiththeJSlider.Theeventhandlercallsmethod

setDiameterinclassOvalPaneltosetthediameterandcallsrepaintto

drawthenewcircle.TherepaintcallresultsinacalltoOvalPanel's

paintComponentmethod.



Figure22.2.JPanelsubclassfordrawingcirclesof

aspecifieddiameter.

(Thisitemisdisplayedonpage1008intheprintversion)



1//Fig.22.2:OvalPanel.java

2//AcustomizedJPanelclass.

3importjava.awt.Graphics;

4importjava.awt.Dimension;

5importjavax.swing.JPanel;

6

7publicclassOvalPanelextendsJPanel

8{

9privateintdiameter=10;//defaultdiameterof10

10

11//drawanovalofthespecifieddiameter



12publicvoidpaintComponent(Graphicsg)

13{

14super.paintComponent(g);

15

16g.fillOval(10,10,diameter,diameter);//drawcircle

17}//endmethodpaintComponent

18

19//validateandsetdiameter,thenrepaint

20publicvoidsetDiameter(intnewDiameter)

21{

22//ifdiameterinvalid,defaultto10

23diameter=(newDiameter>=0?newDiameter:10);

24repaint();//repaintpanel

25}//endmethodsetDiameter

26

27//usedbylayoutmanagertodeterminepreferredsize

28publicDimensiongetPreferredSize()

29{

30returnnewDimension(200,200);

31}//endmethodgetPreferredSize

32

33//usedbylayoutmanagertodetermineminimumsize

34publicDimensiongetMinimumSize()

35{

36returngetPreferredSize();

37}//endmethodgetMinimumSize

38}//endclassOvalPanel



Figure22.3.JSlidervalueusedtodeterminethe

diameterofacircle.

(Thisitemisdisplayedonpage1009intheprintversion)



1//Fig.22.3:SliderFrame.java

2//UsingJSliderstosizeanoval.

3importjava.awt.BorderLayout;

4importjava.awt.Color;

5importjavax.swing.JFrame;

6importjavax.swing.JSlider;

7importjavax.swing.SwingConstants;

8importjavax.swing.event.ChangeListener;

9importjavax.swing.event.ChangeEvent;

10

11publicclassSliderFrameextendsJFrame

12{

13privateJSliderdiameterJSlider;//slidertoselectdiameter

14privateOvalPanelmyPanel;//paneltodrawcircle

15



16//no-argumentconstructor

17publicSliderFrame()

18{

19super("SliderDemo");

20

21myPanel=newOvalPanel();//createpaneltodrawcircle

22myPanel.setBackground(Color.YELLOW);//setbackgroundtoyellow

23

24//setupJSlidertocontroldiametervalue

25diameterJSlider=

26newJSlider(SwingConstants.HORIZONTAL,0,200,10);

27diameterJSlider.setMajorTickSpacing(10);//createtickevery10

28diameterJSlider.setPaintTicks(true);//paintticksonslider

29

30//registerJSlidereventlistener

31diameterJSlider.addChangeListener(

32

33newChangeListener()//anonymousinnerclass

34{

35//handlechangeinslidervalue

36publicvoidstateChanged(ChangeEvente)

37{

38myPanel.setDiameter(diameterJSlider.getValue());

39}//endmethodstateChanged

40}//endanonymousinnerclass

41);//endcalltoaddChangeListener

42

43add(diameterJSlider,BorderLayout.SOUTH);//addslidertoframe

44add(myPanel,BorderLayout.CENTER);//addpaneltoframe

45}//endSliderFrameconstructor

46}//endclassSliderFrame



Figure22.4.TestclassforSliderFrame.

(Thisitemisdisplayedonpage1010intheprintversion)



1//Fig.22.4:SliderDemo.java

2//TestingSliderFrame.

3importjavax.swing.JFrame;

4

5publicclassSliderDemo

6{

7publicstaticvoidmain(Stringargs[])

8{

9SliderFramesliderFrame=newSliderFrame();

10sliderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

11sliderFrame.setSize(220,270);//setframesize

12sliderFrame.setVisible(true);//displayframe

13}//endmain



14}//endclassSliderDemo



ClassOvalPanel(Fig.22.2)containsapaintComponentmethod(lines

1217)thatdrawsafilledoval(acircleinthisexample),a

setDiametermethod(lines2025)thatchangesthecircle'sdiameter

andrepaintstheOvalPanel,agetPreferredSizemethod(lines

2831)thatreturnsthepreferredwidthandheightofanOvalPanel

andagetMinimumSizemethod(lines3437)thatreturnsan

OvalPanel'sminimumwidthandheight.



Look-and-FeelObservation22.1

IfanewGUIcomponenthasaminimumwidthandheight

(i.e.,smallerdimensionswouldrenderthecomponent

ineffectiveonthedisplay),overridemethodgetMinimumSize

toreturntheminimumwidthandheightasaninstanceof

classDimension.



SoftwareEngineeringObservation22.1

FormanyGUIcomponents,methodgetMinimumSizeis

implementedtoreturntheresultofacalltothe

component'sgetPreferredSizemethod.



ClassSliderFrame(Fig.22.3)createstheJSliderthatcontrolsthe

diameterofthecircle.ClassSliderFrame'sconstructor(lines

1745)createsOvalPanelobjectmyPanel(line21)andsetsits

backgroundcolor(line22).Lines2526createJSliderobject

diameter-Slidertocontrolthediameterofthecircledrawnonthe

OvalPanel.TheJSliderconstructortakesfourarguments.Thefirst

argumentspecifiestheorientationofdiameterSlider,whichis

HORIZONTAL(aconstantininterfaceSwingConstants).Thesecondand

thirdargumentsindicatetheminimumandmaximuminteger

valuesintherangeofvaluesforthisJSlider.Thelastargument

indicatesthattheinitialvalueoftheJSlider(i.e.,wherethe

thumbisdisplayed)shouldbe10.



[Page1008]

Lines2728customizetheappearanceoftheJSlider.Method

setMajorTick-Spacingindicatesthateachmajor-tickmark

represents10valuesintherangeofvaluessupportedbythe

JSlider.MethodsetPaintTickswithatrueargumentindicates

thatthetickmarksshouldbedisplayed(theyarenotdisplayed

bydefault).Forothermethodsthatareusedtocustomizea

JSlider'sappearance,seetheJSlideron-linedocumentation

(java.sun.com/j2se/5.0/docs/api/javax/swing/JSlider.html).



[Page1009]

JSlidersgenerateChangeEvents(packagejavax.swing.event)in



responsetouserinteractions.Anobjectofaclassthat

implementsinterfaceChangeListener(package

javax.swing.event)anddeclaresmethodstateChangedcan

respondtoChangeEvents.Lines3141registeraChangeListenerto

handlediameterSlider'sevents.WhenmethodstateChanged(lines

3639)iscalledinresponsetoauserinteraction,line38calls

myPanel'ssetDiametermethodandpassesthecurrentvalueofthe

JSliderasanargument.JSlidermethodgetValuereturnsthe

currentthumbposition.



[Page1010]



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 22. GUI Components: Part 2

Tải bản đầy đủ ngay(0 tr)

×