📄 ch18.htm
字号:
<P>Here, <TT>str</TT> is the text string that you want to appearon the button.<P>Like other Java classes, <TT>Button</TT> features methods youcan use to manipulate a button object. You use these methods toretrieve or set the button's text, like this:<BLOCKQUOTE><PRE>String button.getLabel();button.setLabel(str);</PRE></BLOCKQUOTE><H3><A NAME="ExampleAddingaButtontoanApplet">Example: Adding a Button to an Applet</A></H3><P>Adding buttons to your applets is painfully easy. Just createthe button, and then call the <TT>add()</TT> method to add thebutton to the applet. When the applet runs, the user will be ableto interact with the button, generating events that the appletcan respond to as appropriate. For example, suppose that you wantto add a button for setting a font. First, you create a buttonwith an appropriate label, like this:<BLOCKQUOTE><PRE>Button button = new Button("TimesRoman");</PRE></BLOCKQUOTE><P>Then, you call the <TT>add()</TT> method to add the button objectto the applet, like this:<BLOCKQUOTE><PRE>add(button);</PRE></BLOCKQUOTE><P>Now, when the applet appears in your Web page, the user can clickthe button to trigger an event that tells your applet which fontto display.<H3><A NAME="HandlingMultipleButtonEvents">Handling Multiple-Button Events</A></H3><P>In previous applets that contained buttons, you responded to thebutton in the applet's <TT>action()</TT> method. When the userclicked the button, Java called <TT>action()</TT>, and you didwhatever you needed to do in that method. However, what if youhave more than one button? Then, you need some way to figure outwhich button was clicked so the applet can respond properly.<P>As it turns out, the <TT>action()</TT> method delivers two parametersto your program when it's called, as you can see by examiningthe function's signature:<BLOCKQUOTE><PRE>public boolean action(Event evt, Object arg)</PRE></BLOCKQUOTE><P>The first parameter, <TT>evt</TT>, is an <TT>Event</TT> object,and <TT>arg</TT>, the second parameter, is, in the case of a button,the button's label. (The value type of the second parameter changesdepending on the interface object.) The <TT>target</TT> fieldof an <TT>Event</TT> object indicates the type of object thatgenerated the event. To determine the object, you use the <TT>instanceof</TT>keyword, like this:<BLOCKQUOTE><PRE>if (evt.target instanceof Button)</PRE></BLOCKQUOTE><P>If this <TT>if</TT> statement is <TT>true</TT>, it was a buttonobject that generated the event. To determine exactly which buttoncaused the event, you examine the <TT>arg</TT> parameter, likethis:<BLOCKQUOTE><PRE>if (arg == str)</PRE></BLOCKQUOTE><P>In this line, <TT>str</TT> is the button's label. If the comparisonis true, you know exactly which button was clicked.<H3><A NAME="ExampleHandlingMultipleButtonsinanApplet">Example: Handling Multiple Buttons in an Applet</A></H3><P>To get a better understanding of how button events work, takea look at the applet shown in Listing 18.1. ButtonApplet displaysthree buttons in its display area, as shown in Figure 18.3. Wheneveryou click a button with a normal label, its label reverses itself,as shown in Figure 18.4. When you click a button with an alreadyreversed label, all the labels return to their normal state.<P><A HREF="f18-3.gif"><B> Figure 18.3 : </B><I>The ButtonApplet applet displays three buttons.</I></A><P><P><A HREF="f18-4.gif"><B> Figure 18.4 : </B><I>When you click a button with a normal label, the label reverses itself.</I></A><P><HR><BLOCKQUOTE><B>Listing 18.1 ButtonApplet.java: An Applet with MultipleButtons.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class ButtonApplet extends Applet{ Button button1; Button button2; Button button3; public void init() { button1 = new Button("Button1"); button2 = new Button("Button2"); button3 = new Button("Button3"); add(button1); add(button2); add(button3); } public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) HandleButtons(arg); return true; } protected void HandleButtons(Object label) { if (label == "Button1") button1.setLabel("1nottuB"); else if (label == "Button2") button2.setLabel("2nottuB"); else if (label == "Button3") button3.setLabel("3nottuB"); else { button1.setLabel("Button1"); button2.setLabel("Button2"); button3.setLabel("Button3"); } }}</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>ButtonApplet</TT> class from Java's <TT>Applet</TT>class.<BR> Declare three button objects.<BR> Override the <TT>init()</TT> method.<BR> Create the three buttons.<BR> Add the buttons to the applet's display.<BR> Override the <TT>action()</TT> method.<BR> If a button was pressed, call the <TT>HandleButtons()</TT>method.<BR> Tell Java that the event was handled okay.<BR> Define the <TT>HandleButtons()</TT> method.<BR> Convert the size to a string.<BR> if the button's label is normal, reverse it.<BR> Else set all the button's labels back to normal.</BLOCKQUOTE><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Because a program running in a windowed environment cannot takeexclusive control of a computer's resources, applets require specialcontrols to send and retrieve information to and from the user.Two such controls are labels, which enable you to display shorttext strings, and buttons, which enable the user to select commandswith a single mouse click. When clicked, a button object triggersan event that you can capture and respond to in the applet's <TT>action()</TT>method. By writing Java source code to handle the button click,you can implement many types of button-controlled commands inyour applets. In following chapters, you'll learn about otherJava controls, including checkboxes, choice menus, and scrollbars.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What are the two arguments required by the <TT>Label</TT>class's constructor?<LI>What happens to a label's alignment when the size of an appletchanges?<LI>How do you add controls to an applet?<LI>What is the single argument needed by the <TT>Button</TT>class's constructor?<LI>What are the values you can use to set a label's alignment?<LI>What two attributes of a label object can be set using theclass's methods?<LI>How can you change the label displayed in a button control?<LI>When a user clicks a button control, what arguments are receivedby the <TT>action()</TT> method?<LI>In an applet with several button controls, how can you determinewhich button was clicked?<LI>What happens when the user clicks a label?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an applet that displays the label <TT>Java rules!</TT><LI>Write an applet that creates a button control with the label<TT>Command</TT>.<LI>Write an applet that contains three button controls. Whenthe user clicks a button, display the button's label in the areabelow the buttons.<LI>Write an applet that contains two labels and two buttons organizedinto two rows. Each row should start with a label followed bya button. (Hint: The size of the applet given in its HTML documentwill determine how the controls are organized.)<LI>Write an applet called LabelButtonApplet that contains threebuttons and three labels. When the user clicks a button, the associatedlabel should reverse its text. Clicking on a button that's associatedwith a changed label should reverse the text again, back to itsoriginal form. The final applet should look like Figure 18.5.Figure 18.6 shows the applet with two labels changed. (You canfind the solution to this problem in the CHAP18 folder of thisbook's CD-ROM.)</OL><BR><A HREF="f18-5.gif"><B> Figure 18.5 : </B><I>This is the ButtonLabelApplet applet at startup.</I></A><P><P><A HREF="f18-6.gif"><B> Figure 18.6 : </B><I>Here's ButtonLabelApplet after two labels have been reversed.</I></A><P><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 + -