【正文】
osed to be allowed to mark one menu as the help menu。F can be configured to place menu bars at the top of the screen, where Mac users expect to find them. Setting the system property to true activates thisbehavior. It39。 otherwise, the property returnsfalse. TheponentAtIndex property accesses the menu associated with the given index. It is similar to the indexed menu property, except the contents are cast to 4 aComponent. If there is no ponent associated with that index, the getComponentAtIndex( ) accessor returns null. Theponent property returns a reference to this (., the menu bar itself)。 JMenuBar 類將 DefaultSingleSelectionModel用做自身的數(shù)據(jù)模型,因?yàn)橛脩粼谀骋粫r(shí)刻只能喚起( raise)或激活( activate)一個(gè)菜單。 菜單欄布局 有兩種方法可以將菜單欄連接到 Swing 框架或 applet 上。 如果應(yīng)用程序在 Macintosh上運(yùn)行,用戶可以設(shè)置其外觀風(fēng)格,按自己的意愿把菜單欄放到屏幕頂部。這意味著可以和其他 Swing 組件一樣,通過 Swing 的布局管理器實(shí)現(xiàn)菜單欄定位。但這樣就影響了外觀風(fēng)格在適當(dāng)?shù)臅r(shí)機(jī)給菜單欄妥善定位。ponentAtIndex屬性可訪問與給定索引有關(guān)的菜單,它與被索引的 menu屬性相似,只是它的內(nèi)容被拋給一個(gè) Component 對(duì)象。 另一種方法是,程序員給每個(gè)菜單項(xiàng)注冊(cè)一個(gè)獨(dú)立的 ActionListener 類,來判斷哪個(gè)菜單項(xiàng)被選中。 盡管 SDK 之前的版本無法直接從 Action 構(gòu)造 JMenuItem,但是使用添加Action 到 JMenu或 JPopupMenu的方法可以達(dá)到同樣的效果 —— 菜單自會(huì)妥善創(chuàng)建并配置 JMenuItem。最面向?qū)ο蟮姆椒ㄊ莿?chuàng)建一個(gè)專門的 Action 類,讓它應(yīng)對(duì)用戶可能向應(yīng)用程序提交的所有任務(wù),從而讓程序員把實(shí)現(xiàn)每個(gè)動(dòng)作的程序代碼與動(dòng)作的名稱、圖標(biāo)、按鍵及其他屬性 9 捆綁為一體。 ponent屬性返回一個(gè)對(duì) this的引用(即菜單欄本身), subElements 屬性返回由菜單欄中各個(gè)菜單組成的數(shù)組。如果程序中還包含多重菜單欄,大概就更熱鬧了。 ().add(menuBar, )。但是,在默認(rèn)情況下此狀態(tài)是被禁止的,因?yàn)榇蠖鄶?shù) Java 程序并不期待出現(xiàn)這種情況,而且必須對(duì)程序適當(dāng)編碼才可處理該狀態(tài)。 JMenuBar menuBar = new JMenuBar()。圖 144顯示了 JMenuBar組件的類層次結(jié)構(gòu)( class hierarchy)。s getActionCommand( ) method to obtain the action mand of the menu item generating the event. This tells the listener which menu item has been clicked, allowing it to react accordingly. This is the approach used in earlier in this chapter , which is discussed later. Alternatively, you can register a separate ActionListener class with each menu item, which takes the guesswork out of determining the menu item selected. However, Swing allows you to go a step further. The most objectoriented approach is to create a specialized Action class that corresponds to each of the tasks a user might request of your application. This lets you bundle the code for each program action together wi