⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch6.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
&lt;/applet&gt;</PRE></BLOCKQUOTE><HR><H3><A NAME="ExampleCreatingandRunningApplet">Example: Creating and Running Applet1</A></H3><P>In the next section, you'll see exactly how the Applet1 appletworks. But before you get too much farther, you need to know howto create and run the many applets that you'll find in this book.All the applets that follow use the same sort of procedure. Thisprocedure involves creating the applet's source code, compilingthe code, and then writing the HTML document that demonstratesthe applet. Follow the steps below to get the Applet1 applet upon your screen.<OL><LI>Create a folder called CLASSES on the root directory of yourhard drive.<LI>Type Listing 6.1 and save it in the CLASSES folder as an ASCIIfile. Name the file <TT>Applet1.java</TT>. (Use uppercase andlowercase letters exactly as shown for the program's file name.)Note that you can also copy the listing from this book's CD-ROM,if you don't want to type it.<LI>Start an MS-DOS session by selecting Start/Programs/MS-DOSPrompt. If the MS-DOS screen takes over the entire screen, pressAlt+Enter to display the MS-DOS session in a window.<LI>If you haven't added the JAVA\BIN path to your AUTOEXEC.BATfile, type <TT>PATH=JAVA\BIN</TT> at the MS-DOS prompt. This ensuresthat the system will be able to find Java's executables.<LI>Type <TT>cd c:\classes</TT> to move to your CLASSES folder.<LI>Type <TT>javac Applet1.java</TT> to compile the Applet1 applet.You should receive no error messages, as shown in Figure 6.3.If you do receive error messages, carefully check your typingof Listing 6.1. Also, make sure you typed the command line <TT>javacApplet1.java</TT> properly. When the compiler finishes, you'llhave the file <TT>Applet1.class</TT> in your CLASSES directory.This is the applet's byte-code file.<BR><A HREF="f6-3.gif"><B> Figure 6.3 : </B><I>The Applet1.class file must compile with no errors.</I></A><P><LI>Type Listing 6.2 and save it as an ASCII file to your CLASSESfolder. Name the file APPLET1.htmL. (This time, the case of theletters doesn't matter.)<LI>At the MS-DOS prompt, type <TT>appletviewer applet1.html</TT>(case doesn't matter). When you do, Appletviewer will load anddisplay the applet.</OL><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Java insists that the name of a Java source-code file is the same name as the class contained in the file. If you try to use different names, even if the difference is only the case of a letter or two, the Java compiler will complain and refuse to compile the program.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="HowAppletWorks">How Applet1 Works</A></H3><P>By now, you have the source code for Applet1 properly typed andcompiled. You've even run the applet using Appletviewer. You knowthat the call to the <TT>drawString()</TT> method prints a stringas graphical text in the applet's display area. But what are thevalues between <TT>drawString()</TT>'s parentheses? And how doesthe program know when to execute the call to <TT>drawString()</TT>?<P>First, look at the <TT>paint()</TT> method. Java calls <TT>paint()</TT>whenever the applet's display area (or canvas, as it's often called)needs to be redrawn. The <TT>paint()</TT> method always gets calledwhen the applet first appears on the screen, which is exactlywhat's happening in Applet1. You run the applet, Java calls <TT>paint()</TT>when the applet appears, and <TT>paint()</TT> calls <TT>drawString()</TT>,which displays the text string &quot;Hello from Java.&quot;<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The Java compiler is case-sensitive, meaning that it can differentiate between upper- and lowercase letters. For this reason, you have to be extra careful to type method names properly. For example, if you type <TT>Paint()</TT> instead of <TT>paint()</TT>, Java will not recognize the method and will not call it when the applet needs to be redrawn.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>What's that &quot;g&quot; followed by a period in front of thecall to <TT>drawString()</TT>? Remember that I said <TT>drawString()</TT>is a method of the <TT>Graphics</TT> class. If you look at thefirst line of the <TT>paint()</TT> method, you'll see <TT>Graphicsg</TT> in the parentheses. This means that Java is sending anobject of the <TT>Graphics</TT> class to the <TT>paint()</TT>method and that object is called <TT>g</TT>. Whenever you needto call an object's method, you must preface the method's namewith the object's name followed by a period. So, the line<BLOCKQUOTE><PRE>g.drawString(&quot;Hello from Java!&quot;, 60, 75);</PRE></BLOCKQUOTE><P>tells Java to call the <TT>g</TT> object's <TT>drawString()</TT>method. The values in the parentheses are called arguments, whichare values that you need to send to the method. The argumentsin the above call to <TT>drawString()</TT> tell Java to draw thetext &quot;Hello from Java!&quot; at column 60 and row 75 of thedisplay area. (The position is measured in pixels, not characters.A pixel is the smallest dot that can be displayed on the screen.)To display the text at a different location, just change the secondand third arguments. For example, Figure 6.4 shows the text positionedat 25,25.<P><A HREF="f6-4.gif"><B> Figure 6.4 : </B><I>Here, Applet1 displays the text at position 25,25.</I></A><P><H2><A NAME="GettingInputfromtheUser"><FONT SIZE=5 COLOR=#Ff0000>Getting Input from the User</FONT></A></H2><P>Again, because you are now programming in a graphical environment,getting input from the user isn't as easy as just calling an inputcommand. You must first create an area of the screen in whichthe user can type and edit his response to your request. Thereare several ways to do this, but one of the easiest is to adda control of the <TT>TextField</TT> class in your applet. A <TT>TextField</TT>control is much like the edit boxes you see when using Windows.You might, for example, see a number of edit controls in a dialogbox. Listing 4.3 shows how to include a <TT>TextField</TT> controlin your applet. Figure 6.5 shows the Applet2 applet in action.<P><A HREF="f6-5.gif"><B> Figure 6.5 : </B><I>The Applet2 applet displays an area in which you can type.</I></A><P><HR><BLOCKQUOTE><B>Listing 6.3&nbsp;&nbsp;Applet2.java: Getting Input from theUser.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet2 extends Applet{    TextField textField;    public void init()    {        textField = new TextField(20);        add(textField);    }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the program uses classes in the <TT>awt</TT> package.<BR>Tell Java that the program uses classes in the <TT>applet</TT>package.<BR>Derive the <TT>Applet2</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare <TT>textField</TT> as an object of the <TT>TextField</TT>class.<BR>    Override the <TT>Applet</TT> class's <TT>init() </TT>method.<BR>        Create the new <TT>TextField</TT> object.<BR>        Add the <TT>TextField</TT> object to the applet's display.</BLOCKQUOTE><P>To run the Applet2 applet yourself, you'll need to type and savethe source code, naming it <TT>Applet2.java</TT>. (You can copythe source code from the CD-ROM, if you like, and thus save ontyping. Of course, you won't learn as much that way.) Then compilethe source code (type <TT>javac Applet2.java</TT> at the MS-DOSprompt), which gives you the <TT>Applet2.class</TT> file. Next,create a new HTML document from the one shown in Listing 6.2,changing all instances of Applet1 to Applet2. You can then runApplet2 by typing <TT>appletviewer applet2.html</TT> at the DOSprompt.<H3><A NAME="HowAppletWorks1">How Applet2 Works</A></H3><P>Applet2 looks quite a bit different from Applet1. First, it declaresa data field named <TT>textField</TT> as an object of the <TT>TextField</TT>class, which represents a control very much like a standard Windowsedit box. The program declares the control like this:<BLOCKQUOTE><PRE>TextField textField;</PRE></BLOCKQUOTE><P>Notice that the <TT>textField</TT> object is declared just asyou would declare any other kind of data object such as an integeror a floating-point value. Next, notice that, although the nameof the class and the name of the object are spelled identically,the object's name starts with a lowercase letter. This makes allthe difference in the world to Java, which is a case-sensitivelanguage.<P>Another difference between Applet1 and Applet2 is that Applet2has an <TT>init()</TT> method instead of <TT>paint()</TT>. The<TT>Init()</TT> method is another of those methods that Java callsautomatically-in this case, as soon as you run the Applet2 applet.Because Java calls <TT>init()</TT> almost immediately, it's agreat place to initialize the applet. (Guess that's why they calledit <TT>init()</TT>, huh?)<P>In Applet2, when <TT>init()</TT> gets called, <TT>textField</TT>has already been declared as an object of the <TT>TextField</TT>class, but <TT>textField</TT> hasn't yet been assigned a value.The first line of code in <TT>init()</TT> creates the <TT>TextField</TT>object and assigns it to <TT>textField</TT>, like this:<BLOCKQUOTE><PRE>textField = new TextField(20);</PRE></BLOCKQUOTE><P>After Java executes this line, <TT>textField</TT> refers to anactual <TT>TextField</TT> object. The value in the parenthesesis the width of the <TT>TextField</TT> control; the larger thisnumber, the wider the control. Keep in mind that a <TT>textField</TT>control can hold more text than its width allows. If you typepast the end of the control's text box, the text scrolls horizontally.<P>The next step is to add the object to the applet's display area,like this:<BLOCKQUOTE><PRE>add(textField);</PRE></BLOCKQUOTE><P>The <TT>add()</TT> method's single argument is the control youwant to add to the applet.<P>After creating the control and adding it to the applet, the controlwill automatically appear when Java draws the applet. You don'tneed a <TT>paint()</TT> method to draw a control, because thecontrol can take care of itself.<P>Once the <TT>TextField</TT> control is on the screen, you cantype in it. First, click the control to give it the focus, thentype and edit to your heart's content.<H3><A NAME="ExampleRetrievingtextfromaITextFieldIcontrol">Example: Retrieving text from a <I>TextField</I> control</A></H3><P>In the Applet2 applet, you can type all you like in the <TT>TextField</TT>control, but how do you get the text out of the control and actuallydo something with it? Follow the steps below to create Applet3,a new version of Applet2 that can retrieve and display any textentered into the <TT>TextField</TT> control.<OL>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -