📄 ch32.htm
字号:
for (int x=0; x<count; ++x) System.out.println(message); } public static void main(String args[]) { ArgApp app = new ArgApp(); app.GetArgs(args); app.PrintMessage(); }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Declare the <TT>ArgApp</TT> class.<BR> Declare the class's data fields.<BR> Define the <TT>GetArgs()</TT> method.<BR> Extract the number of times to print the message.<BR> Convert the count to an integer.<BR> Extract the message to print.<BR> Define the <TT>PrintMessage()</TT> method.<BR> Loop for the requested number of times.<BR> Display the message each time through the loop.<BR> Define the app's<TT> main()</TT> method.<BR> Create an <TT>ArgApp()</TT> object.<BR> Call the method to extract the arguments.<BR> Call the method to print the message.</BLOCKQUOTE><P>The ArgApp application not only shows you how to use command-lineparameters, but also how to write a Java application that actuallydoes something. The important thing to notice here is that youmust first create an object of the ArgApp class before you cancall its methods and access its data fields. This is because aclass is just a template for an object; it doesn't actually becomean object until you create an instance of the class with the <TT>new</TT>keyword.<P>One way to avoid having to create an object of the class is todeclare all the class's data fields and methods as <TT>static</TT>.Such methods and data fields are accessible in memory, which iswhy the SimpleApp application in Listing 31.1 runs. Its <TT>main()</TT>method is declared as <TT>static</TT>. Of course, it's a heckof a lot easier to just go ahead and create an object of the classthan it is to go through the source code and add <TT>static</TT>to everything.<H2><A NAME="WindowedApplications"><FONT SIZE=5 COLOR=#Ff0000>Windowed Applications</FONT></A></H2><P>You're probably thinking that it's pretty much a waste of timeto write Java applications if you have to run them under the DOSor UNIX text-based operating system. All the action these daysis in windowed applications. Yes, you can write windowed applicationswith Java, as the HotJava browser proves. But, if you've writtenconventional windowed applications, you're probably a little nervousabout writing similar Java applications. After all, writing suchapplications with languages like C and C++ can be a nightmare.<P>The truth is, however, you already know almost everything youneed to know to write your own standalone applications for GUIoperating systems. You can take most any applet and convert itto a standalone application just by adding the <TT>main()</TT>method to the class. In <TT>main()</TT>, you have to perform someof the tasks that Java handles for you when running an applet.These tasks include creating, sizing, and displaying the application'swindow. The following example gives you the details.<H3><A NAME="ExampleChanginganApplettoanApplication">Example: Changing an Applet to an Application</A></H3><P>As I said in the previous paragraph, you can convert almost anyapplet to an application simply by adding a <TT>main()</TT> methodthat performs a few housekeeping tasks. Listing 32.3 is an appletfrom a previous chapter's exercises. The previous version drewa face image in the applet's display. The new version displaysthe face in its own standalone, frame window. When you run theapplication, you see the window shown in Figure 32.4.<P><A HREF="f32-4.gif"><B> Figure 32.4 : </B><I>The FaceApp application draws a face in a frame window.</I></A><P><HR><BLOCKQUOTE><B>Listing 32.3 FaceApp.java: Converting an Appletto an Application.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class FaceApp extends Applet{ public void init() { Button button = new Button("Close"); add(button); } public void paint(Graphics g) { // Head. g.drawOval(40, 40, 120, 150); // Eyes. g.drawOval(57, 75, 30, 20); g.drawOval(110, 75, 30, 20); // Pupils. g.fillOval(68, 81, 10, 10); g.fillOval(121, 81, 10, 10); // Nose. g.drawOval(85, 100, 30, 30); // Mouth. g.fillArc(60, 130, 80, 40, 180, 180); // Ears. g.drawOval(25, 92, 15, 30); g.drawOval(160, 92, 15, 30); } public boolean action(Event evt, Object arg) { if (arg == "Close") System.exit(0); return true; } public static void main(String args[]) { FaceApp app = new FaceApp(); Frame frame = new Frame("Face Window"); app.init(); app.start(); frame.add("Center", app); frame.resize(210, 300); frame.show(); }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the class uses the <TT>awt</TT> package.<BR>Tell Java that the class uses the <TT>applet</TT> package.<BR>Declare the <TT>FaceApp</TT> class.<BR> Override the <TT>init()</TT> method.<BR> Create a button object and add it to the window.<BR> Override the <TT>paint() </TT>method.<BR> Draw the face image using ovals and arcs.<BR> Override the <TT>action()</TT> method.<BR> If the user clicks the close button...<BR> Shut down the application.<BR> Tell Java the message was handled.<BR> Define the <TT>main()</TT> method.<BR> Create the <TT>FaceApp</TT> object and the frame window.<BR> Call the <TT>init()</TT> and <TT>start()</TT> methods.<BR> Add the "applet" to the window.<BR> Size and show the window.</BLOCKQUOTE><H3><A NAME="UnderstandingtheFaceAppApplication">Understanding the FaceApp Application</A></H3><P>If you examine Listing 32.3, you'll see that most of the FaceAppapplication is written exactly like any other applet you've writtenthroughout this book. The big difference is the addition of the<TT>main()</TT> method, where this program's execution starts.Because you're no longer running the program as an applet, youhave to perform some of the start-up tasks that Java automaticallyperforms for applets. The first step is to create an object ofthe class and a frame window to hold the object, like this:<BLOCKQUOTE><PRE>FaceApp app = new FaceApp();Frame frame = new Frame("Face Window");</PRE></BLOCKQUOTE><P>Next, you have to call the methods that get the object going.These methods are <TT>init()</TT> and <TT>start()</TT>, whichare usually called by Java:<BLOCKQUOTE><PRE>app.init();app.start();</PRE></BLOCKQUOTE><P>Note that, although the FaceApp class doesn't show a <TT>start()</TT>method, it does inherit it from the <TT>Applet</TT> class. It'strue that even the inherited <TT>start()</TT> method doesn't doanything, but you might as well be consistent and call it anyway.That way, you won't forget that some applets do override the <TT>start()</TT>method, without which they won't run properly.<P>Now, you can add the FaceApp object to the frame window, likethis:<BLOCKQUOTE><PRE>frame.add("Center", app);</PRE></BLOCKQUOTE><P>Finally, you must be sure to resize and show the window, likethis:<BLOCKQUOTE><PRE>frame.resize(210, 300);frame.show();</PRE></BLOCKQUOTE><P>If you fail to resize the application's window, all you'll seeis the title bar, forcing the user to resize the window by hand.More importantly, if you fail to call <TT>show()</TT>, the application'swindow won't even appear on the screen. That's sure to leave yourapplication's user feeling abused.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Although Java is used almost exclusively for creating applets,it is possible to use Java to create standalone applications.These applications can be DOS-based (or UNIX, etc.) or be writtenfor a windowed operating system such as Windows 95. The easiestway to create a windowed application is to write the program asif it were an applet and then add a <TT>main()</TT> method thatcreates the application object and the frame window that'll containthat object.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What method do you find in an application that you don't findin an applet?<LI>How do you run a Java standalone application?<LI>What is the single parameter received by the <TT>main()</TT>method?<LI>How can you extract parameters from an application's commandline?<LI>What do you have to add to an applet to convert it to an application?<LI>Why do you have to instantiate an object from a class beforeyou can call its methods?<LI>What do you have to do to create and display an application'swindow?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write a stand-alone application that accepts two numbers asparameters and prints out the numbers' sum.<LI>Choose any applet from this book and convert it to a stand-aloneapplication.<LI>Convert the ThreadApplet5 applet from <A HREF="ch31.htm" >Chapter 31</A>'s exercisesinto a stand-alone application. (You can find the solution forthis exercise in the CHAP32 folder of this book's CD-ROM.)</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 + -