计算机外文翻译 菜单和工具栏大学论文Word文档下载推荐.docx
《计算机外文翻译 菜单和工具栏大学论文Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《计算机外文翻译 菜单和工具栏大学论文Word文档下载推荐.docx(6页珍藏版)》请在冰豆网上搜索。
Excerptedfrom"
JavaSwing(2NdEdition)(O'
Reilly)"
byMarcLoy,RobertEcksteinetc.
TheJMenuBarClass
Swing'
sJMenuBarclasssupersedestheAWTMenuBarclass.Thisclasscreatesahorizontalmenubarcomponentwithzeroormoremenusattachedtoit.JMenuBarusestheDefaultSingleSelectionModelasitsdatamodelbecausetheusercanraise,oractivate,onlyoneofitsmenusatagiventime.Oncethemousepointerleavesthatmenu,theclassremovesthemenufromthescreen(orcancelsit,inSwinglingo),andallmenusagainbecomeeligibletoberaisedFigure14-4showstheclasshierarchyfortheJMenuBarcomponent.
Figure14-4.JMenuBarclassdiagram
YoucanaddJMenuobjectstothemenubarwiththeadd()methodoftheJMenuBarclass.JMenuBarthenassignsanintegerindexbasedontheorderinwhichthemenuswereadded.Themenubardisplaysthemenusfromlefttorightonthebaraccordingtotheirassignedindex.Intheory,thereisoneexception:
thehelpmenu.Youaresupposedtobeallowedtomarkonemenuasthehelpmenu;
thelocationofthehelpmenuisuptotheL&
F.Inpractice,tryingtodothisresultsinJMenuBarthrowinganError.
MenuBarPlacement
YoucanattachmenubarstoSwingframesorappletsinoneoftwoways.First,youcanusethesetJMenuBar()methodofJFrame,JDialog,JApplet,orJInternalFrame:
JFrameframe=newJFrame("
Menu"
);
JMenuBarmenuBar=newJMenuBar();
//Attachthemenubartotheframe.
frame.setJMenuBar(menuBar);
ThesetJMenuBar()methodisanalogoustothesetMenuBar()methodofjava.awt.Frame.Likeitspredecessor,setJMenuBar()allowstheL&
Ftodeterminethelocationofthemenu(typically,itanchorsthemenubartothetopofaframe,adjustingtheframe'
sinternalInsetsaccordingly).BothJAppletandJDialogcontainasetJMenuBar()method—thismeansthatyoucanaddmenubarstobothappletsanddialogs.Eitherway,besurenottoconfusethesetJMenuBar()methodwiththeoldersetMenuBar()methodofAWTwhenworkingwithSwingmenus,orthecompilercomplainsbitterly.
IfyourapplicationisrunningonaMacintosh,theMacL&
Fcanbeconfiguredtoplacemenubarsatthetopofthescreen,whereMacusersexpecttofindthem.Settingthesystempropertycom.apple.macos.useScreenMenuBartotrueactivatesthisbehavior.It'
sdisabledbydefaultbecausemostJavaprogramsdonotexpectthisbehavior,andtheymustbecodedproperlytodealwithit.Notably,theAquaHumanInterfaceGuidelinesrequirethatthemenubarisalwaysvisible.Ifyourapplicationhasanyframesthatlackmenubars,wheneveroneofthesegainsfocus,itcausesthemenubartodisappear,muchtotheuser'
sconsternation.Themostcommonwayofdealingwiththisistowriteamenufactorythatgeneratesanidenticalmenubarforeachframeyourapplicationuses.Althoughthisisalittleextrawork,thefamiliarityandcomfortitbringsyourMacusersisprobablyworthit.
Thesecondwaytoaddamenubarismuchlesscommon.RecallthattheJMenuBarclassextendsJComponent.ThismeansitcanbepositionedbyaSwinglayoutmanagerlikeotherSwingcomponents.Forexample,wecouldreplacethecalltosetJMenuBar()withthefollowingcode:
menuBar.setBorder(newBevelBorder(BevelBorder.RAISED));
frame.getContentPane().add(menuBar,BorderLayout.SOUTH);
Figure14-5.JMenuBarpositionedasaSwingcomponent
Thisplacesthemenubaratthebottomoftheframe,asshowninFigure14-5.(Notethatwesetabeveledborderaroundthemenubartohelpoutlineitslocation.)Itwouldevenbepossibletoaddtwoorthreemenubarsindifferentlocations.Swingdoesnotrequireasinglemenubartobeanchoredtothetopofaframe.BecausetheyextendJComponent,multiplemenubarscanbepositionedanywhereinsideacontainer.
Ofcourse,you'
dneveractuallywanttodothiswithoutaverycompellingreason.ItrobstheL&
Fofitsopportunitytoplacethemenubarintheappropriatelocation.Movingsomethingasfundamentalasamenubarisalmostcertaintocauseconfusionandusabilitychallengesforyourusers;
havingmultiplemenubarswouldbebaffling.
Properties
ThepropertiesoftheJMenuBarclassareshowninTable14-3.menuisanindexedpropertythatreferenceseachJMenuattachedtothemenubar.Theread-onlymenuCountpropertymaintainsacountoftheseattachedmenus.Rememberthatthesingleselectionmodelallowsonlyonemenutobeactivatedatatime.Ifanymenuiscurrentlyactivated,theselectedpropertyreturnstrue;
otherwise,thepropertyreturnsfalse.ThecomponentAtIndexpropertyaccessesthemenuassociatedwiththegivenindex.Itissimilartotheindexedmenuproperty,exceptthecontentsarecasttoaComponent.Ifthereisnocomponentassociatedwiththatindex,thegetComponentAtIndex()accessorreturnsnull.Thecomponentpropertyreturnsareferencetothis(i.e.,themenubaritself);
subElementsreturnsanarrayconsistingofthemenusonthemenubar.
TheJMenuItemClass
EventHandling
Thereareanumberofwaystoprocesseventsfrommenuitems.BecausemenuitemsinheritActionEventfunctionalityfromAbstractButton,oneapproachistoassignanactioncommandtoeachmenuitem(thisisoftendoneautomaticallywithnamedcomponents)andattachallofthemenuitemstothesameActionListener.Then,intheactionPerformed()methodofthelistener,usetheevent'
sgetActionCommand()methodtoobtaintheactioncommandofthemenuitemgeneratingtheevent.
Thistellsthelistenerwhichmenuitemhasbeenclicked,allowingittoreactaccordingly.ThisistheapproachusedinIntroExample.javaearlierinthischapterandPopupMenuExample.java,whichisdiscussedlater.
Alternatively,youcanregisteraseparateActionListenerclasswitheachmenuitem,whichtakestheguessworkoutofdeterminingthemenuitemselected.However,Swingallowsyoutogoastepfurther.Themostobject-orientedapproachistocreateaspecializedActionclassthatcorrespondstoeachofthetasksausermightrequestofyourapplication.Thisletsyoubundlethecodeforeachprogramactiontogetherwiththeaction'
sname,icon,keystrokes,andotherattributesinoneplace.YoucanthenusethisActiontocreatethemenuitem,whichautomaticallysetstheitem'
stext,image,accelerator,andsoon.
Thistechniqueisparticularlypowerfulifyouwanttobeabletoinvokethesameactioninmultipleways(suchasfromatoolbaraswellasamenu).YoucanusethesameActioninstancetocreatethemenuitemandtoolbarbutton,andthey'
llbothhaveappropriatelabelsandappearances.Iftheapplicationneedstodisabletheactionbecauseit'
snotcurrentlyappropriate,callingsetEnabledontheActioninstanceautomaticallyupdatesalluserinterfaceelementsassociatedwiththeaction(thusdimmingbothyourmenuitemandtoolbarbutton).Similarly,changingotherattributesoftheaction,suchasitsnameoricon,automaticallyupdatesanyassociateduser-interfacecomponents.
AlthoughpriortoSDK1.3itwasn'
tpossibletoconstructaJMenuItemfromanActiondirectly,addingtheActiontoaJMenuorJPopupMenuhadthesameeffect:
themenuwouldcreateandconfigureanappropriateJMenuItemforyou.
菜单和工具栏
摘自《JavaSwing》(第二版)MarcLoy,RobertEckstein等著
JMenuBar类
Swing的JMenuBar类是AWT的MenuBar类的替代产品,它创建一个水平菜单栏组件,其中可连接零个以上菜单。
JMenuBar类将DefaultSingleSelectionModel用做自身的数据模型,因为用户在某一时刻只能唤起(raise)或激活(activate)一个菜单。
而且,只要鼠标指针离开菜单,该类就把菜单从屏幕上去除(或按照Swing说法,将其“取消”),所有菜单又恢复为可以被唤起的状态。
图14-4显示了JMenuBar组件的类层次结构(classhierarchy)。
Figure14-4JMenuBar类图
程序员可以用JMenuBar类的add()方法添加JMenu对象。
JMenuBar便随之分配一个整数索引,里面的菜单按照其加入索引的顺序排列,而菜单栏则依照此索引内容的顺序从左至右显示菜单。
从理论上讲,帮助菜单是惟一的例外。
程序员应该让某一个菜单被标记为帮助菜单,但帮助菜单的位置由外观风格决定。
在实践中,如果程序员越俎代庖,JMenuBar就会抛出一个Error对象。
菜单栏布局
有两种方法可以将菜单栏连接到Swing框架或applet上。
第一,使用JFrame、JDialog、JApplet或JInternalFrame的setJMenuBar()方法:
JMenuBarmenuBar=newJMenuBar();
//themenubartotheframe.
这段程序中的setJMenuBar()方法类似于java.awt.Frame的setMenuBar()方法。
与老版本一样,setJMenuBar()也让外观风格来确定菜单的位置(一般情况下,它会将菜单栏锚定在框架顶部,并对框架的固有Insets做适当调整)。
JApplet和JDialog都包含setJMenuBar()方法,这也就是说,applet和对话框中都可以添加菜单栏。
不管怎样,程序员在使用Swing菜单时千万不要混淆setJMenuBar()方法和老版的AWTsetMenuBar()方法,否则编译器一定吃不消。
如果应用程序在Macintosh上运行,用户可以设置其外观风格,按自己的意愿把菜单栏放到屏幕顶部。
系统属性com.apple.macos.useScreenMenuBar为true时,该状态即被激活。
但是,在默认情况下此状态是被禁止的,因为大多数Java程序并不期待出现这种情况,而且必须对程序适当编码才可处理该状态。
尤其要注意的是,Aqua人机界面规范(AquaHumanInterfaceGuidelines)要求菜单栏始终可见。
如果应用程序的某个框架没有菜单栏,那么,当该窗口获得输入焦点时,菜单栏会立刻消失,让用户不知所措。
解决这一问题最普遍的方法是编写一个菜单工厂(menufactory),为应用程序用到的每个框架生成一个同样的菜单栏。
尽管这样做增大了程序员的工作量,但为了给Mac用户呈现一个亲切、舒适的界面,多做点工作还是值得的。
连接菜单栏的第二种方法是调用JComponent的子类JMenuBar类,这种方法相比之下用得不多。
这意味着可以和其他Swing组件一样,通过Swing的布局管理器实现菜单栏定位。
举例来说,我们可以用下列代码替换对setJMenuBar()的调用:
frame.getContentPane().add(menuBar,BorderLayout.SOUTH);
Figure14-5按Swing组件的方式定位JMenuBar
这样一来,菜单栏被置于框架底部,如图14-5所示(请注意,设置环绕菜单栏的斜面边框是为了突出菜单栏的位置)。
甚至还可以在不同的位置添加多个菜单栏。
Swing不要求将单个菜单栏锚定在框架顶部。
由于都是JComponent的子类,所以多重(multiple)菜单栏可以位于容器内的任何位置。
当然,如果没有强制性的理由,程序员是不会照此办理的。
但这样就影响了外观风格在适当的时机给菜单栏妥善定位。
移动菜单栏这类基础组件,几乎总是会让用户手忙脚乱,不知该如何操作。
如果程序中还包含多重菜单栏,大概就更热闹了。
属性
JMenuBar类的属性如表14-3所示。
其中,menu属性是一个索引属性(indexedproperty),引用了每一个连接到菜单栏的JMenu对象。
只读属性menuCount则存放被连接菜单的数目。
请记住,单个选择模型只允许每次激活一个菜单。
如果当前有菜单被激活,selected属性返回true;
否则返回false。
componentAtIndex属性可访问与给定索引有关的菜单,它与被索引的menu属性相似,只是它的内容被抛给一个Component对象。
如果没有组件与索引相关,getComponentAtIndex()存取方法将返回null值。
component属性返回一个对this的引用(即菜单栏本身),subElements属性返回由菜单栏中各个菜单组成的数组。
JMenuItem类
事件处理
处理菜单项事件的方法有很多种。
鉴于菜单项从AbstractButton处继承了ActionEvent功能,因而一个可行的方法便是为每个菜单项赋予一个操作指令(这通常由指定组件自动完成),并将所有菜单项连接到同一个ActionListener方法上。
接下来,在监听器的actionPerformed()方法中调用事件的getActionCommand()方法获取