📄 ch23.htm
字号:
<BLOCKQUOTE><PRE>MenuItem option1 = new MenuItem("Option 1");MenuItem option2 = new MenuItem("Option 2");MenuItem option3 = new MenuItem("Option 3");</PRE></BLOCKQUOTE><P>The <TT>MenuItem</TT> constructor takes as its single argumentthe string that'll be displayed in the menu for this item.<P>If you're thinking that, after you create the menu items, youmust call the appropriate <TT>Menu</TT> object's <TT>add( )</TT>method, you're be exactly right. Those lines might look like this:<BLOCKQUOTE><PRE>optionMenu.add(option1);optionMenu.add(option2);optionMenu.add(option3);</PRE></BLOCKQUOTE><P>Now, when you display the frame window sporting the menu bar you'vejust created, you'll see that the Options menu contains a numberof selections from which the user can choose, as shown in Figure23.5.<P><A HREF="f23-5.gif"><B> Figure 23.5 : </B><I>Now the Options menu contains menu items.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Sometimes, you may have several groups of related commands that you'd like to place under a single menu. You can separate these command groups by using menu separators, which appear as horizontal lines in a pop-up menu. To create a menu separator, just create a regular <TT>MenuItem</TT> object with a string of "­". That is, the string should contain a single hyphen.</BLOCKQUOTE></TD></TR></TABLE></CENTER><H3><A NAME="ExampleUsingaMenuBarinaFrameWindow">Example: Using a Menu Bar in a Frame Window</A></H3><P>Now that you have this menu bar business mastered, it's time toput what you've learned to work. Listing 23.4 is an applet calledMenuBarApplet. This applet displays a single button, which, whenselected, displays a frame window with a menu bar. This menu barcontains a single menu with three items. The first two items areregular <TT>MenuItem</TT> objects. The third item is <TT>CheckboxMenuItem</TT>,which is a menu item that can display a check mark. Figure 23.6shows MenuBarApplet with its frame window displayed and the Testmenu visible. (Notice the menu separator above the checked item.)<P><A HREF="f23-6.gif"><B> Figure 23.6 : </B><I>This is MenuBarApplet's frame window and menu bar.</I></A><P><HR><BLOCKQUOTE><B>Listing 23.4 MenuBarApplet.java: An Applet ThatUses a Menu Bar.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class MenuBarApplet extends Applet{ MenuBarFrame frame; Button button; public void init() { frame = new MenuBarFrame("MenuBar Window"); button = new Button("Show Window"); add(button); } public boolean action(Event evt, Object arg) { boolean visible = frame.isShowing(); if (visible) { frame.hide(); button.setLabel("Show Window"); } else { frame.show(); button.setLabel("Hide Window"); } return true; }}class MenuBarFrame extends Frame{ MenuBar menuBar; String str; MenuBarFrame(String title) { super(title); menuBar = new MenuBar(); setMenuBar(menuBar); Menu menu = new Menu("Test"); menuBar.add(menu); MenuItem item = new MenuItem("Command 1"); menu.add(item); item = new MenuItem("Command 2"); menu.add(item); item = new MenuItem("-"); menu.add(item); CheckboxMenuItem checkItem = new CheckboxMenuItem("Check"); menu.add(checkItem); str = ""; Font font = new Font("TimesRoman", Font.BOLD, 20); setFont(font); } public void paint(Graphics g) { resize(300, 250); g.drawString(str, 20, 100); } public boolean action(Event evt, Object arg) { if (evt.target instanceof MenuItem) { if (arg == "Command 1") str = "You selected Command 1"; else if (arg == "Command 2") str = "You selected Command 2"; else if (arg == "Check") str = "You selected the Check item"; repaint(); return true; } else return false; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the applet uses the classes in the <TT>awt</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>applet</TT>package.<BR>Derive the <TT>MenuBarApplet</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the custom frame-window and button objects.<BR> Override the <TT>init( )</TT> method.<BR> Create the custom frame window.<BR> Create and add the button component.<BR> Override the <TT>action( )</TT> method.<BR> Determine whether the window is visible.<BR> If the window is visible...<BR> Hide the window.<BR> Change the button's label to "Show Window."<BR> Else if the window is hidden...<BR> Show the window.<BR> Change the button's label to "Hide Window."<BR> Tell Java that the message was handled okay.<BR>Derive the <TT>MenuBarFrame</TT> class from Java's <TT>Frame</TT>class.<BR> Declare the class's menu bar and string objects.<BR> Define the class's constructor.<BR> Pass the title string on to the <TT>Frame</TT> class.<BR> Create and set the menu bar.<BR> Create and add the <TT>Test</TT> menu.<BR> Create and add two regular menu items.<BR> Create and add a menu separator.<BR> Create and add a checkmark menu item.<BR> Initialize the class's display string and font.<BR> Override the window's <TT>paint( ) </TT>method.<BR> Resize the window.<BR> Show the display string in the window.<BR> Override the <TT>action( )</TT> method.<BR> if a menu item was selected...<BR> Respond to the selected menu.<BR> Repaint the window, so the new string is displayed.<BR> Return true if the message was handled.<BR> Or else return false so Java knows the event is unhandled.<BR></BLOCKQUOTE><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>To determine the state (checked or unchecked) of a <TT>CheckboxMenuItem</TT> object, you can call its <TT>getState( )</TT> method. This method returns <TT>true</TT> if the item is checked and <TT>false</TT> if the item is unchecked. In addition, you can set the item's state by calling its <TT>setState( )</TT> method.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>As you can see from MenuBarApplet's source code, you respond tomenu-item selections in the same way you respond to other eventsin applets. This time, however, you have overridden two <TT>action( )</TT>methods. The first is in the <TT>MenuBarApplet</TT> class andhandles the applet's single button. The second overridden <TT>action( )</TT>method, which is the one that handles the menu items, is in the<TT>MenuBarFrame</TT> class.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Although it's an ability you may not frequently take advantageof, Java applets can display windows. The <TT>Frame</TT> classmakes this possible, by providing the functionality for framewindows, which can be sized, moved, used to display components,and much more. A frame window can, in fact, even have a full-featuredmenu bar, just like the menu bars you see in many Windows applications.Creating a menu bar, however, requires knowing how to create andmanipulate <TT>MenuBar</TT>, <TT>Menu</TT>, <TT>MenuItem</TT>,and <TT>CheckboxMenuItem</TT> objects. Luckily, you learned aboutthose classes in this chapter, so you're all ready to amaze theworld with your Java frame windows.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>How do you create a frame window?<LI>How do you display a frame window after you create it?<LI>How can you determine whether a frame window is currentlyvisible?<LI>What's the difference between <TT>MenuItem</TT> and <TT>CheckboxMenuItem</TT>objects?<LI>Which Java class must you extend to create a custom frame-windowclass?<LI>How do you ensure that a custom frame-window class has properlyinitialized its superclass?<LI>How do you draw text or graphics in a frame window?<LI>What are the six steps that must be completed in order toadd a menu bar to a frame window?<LI>How do you add components, such as controls, to a frame window?<LI>How do you respond to selected menu items?<LI>How do you create a menu separator object?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an applet that displays a frame window as soon as theapplet runs.<LI>Write an applet that displays a frame window containing a2x2 grid of buttons.<LI>Modify the applet you wrote in exercise 2 so that the framewindow contains a menu bar with two menus. Each menu should havea single menu item.<LI>Modify the MenuBarApplet so that the menu bar has an additionalmenu called View. This menu should contain a single checkmarkedoption called Window that determines whether a second frame windowis visible on the screen. When the user selects the Window command,the command should be checkmarked and the second window shouldappear. When the user clicks this command a second time, the secondwindow should disappear and the command should be unchecked. Figure23.7 shows the resultant applet in action. (You can find the solutionto this exercise in the CHAP23 folder of this book's CD-ROM.)<BR><A HREF="f23-7.gif"><B> Figure 23.7 : </B><I>This is MenuFrameApplet running under Appletviewer.</I></A><P></OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -