19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

682 Chapter 18 Applets and Multimedia<br />

52<br />

53 // Invoke applet's init method<br />

54<br />

55<br />

applet.init();<br />

applet.start();<br />

56<br />

57 // Display the frame<br />

58 frame.setSize(300, 300);<br />

59 frame.setLocationRelativeTo(null); // Center the frame<br />

60 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />

61 frame.setVisible(true);<br />

62 }<br />

63<br />

64 /** Get <strong>com</strong>mand-line parameters */<br />

65 private void getCommandLineParameters(String[] args) {<br />

66 // Check usage and get x, y and message<br />

67 if (args.length != 3) {<br />

68 System.out.println(<br />

69 "Usage: java DisplayMessageApp x y message");<br />

70 System.exit(1);<br />

71 }<br />

72 else {<br />

73 x = Integer.parseInt(args[0]);<br />

74 y = Integer.parseInt(args[1]);<br />

75 message = args[2];<br />

76 }<br />

77 }<br />

78 }<br />

When you run the program as an applet, the main method is ignored. When you run it as an<br />

application, the main method is invoked. Sample runs of the program as an application and as<br />

an applet are shown in Figure 18.7.<br />

(a)<br />

FIGURE 18.7 The DisplayMessageApp class can run as an applet in (a) and as an<br />

application in (b).<br />

The main method creates a JFrame object frame and creates a JApplet object applet,<br />

then places the applet applet in<strong>to</strong> the frame frame and invokes its init method. The application<br />

runs just like an applet.<br />

The main method sets isStandalone as true (line 45) so that it does not attempt <strong>to</strong><br />

retrieve HTML parameters when the init method is invoked.<br />

The setVisible(true) method (line 61) is invoked after the <strong>com</strong>ponents are added <strong>to</strong><br />

the applet, and the applet is added <strong>to</strong> the frame <strong>to</strong> ensure that the <strong>com</strong>ponents will be visible.<br />

Otherwise, the <strong>com</strong>ponents are not shown when the frame starts.<br />

(b)<br />

omitting main method<br />

✓Point✓ Check<br />

Important Pedagogical Note<br />

From now on, all the GUI examples will be created as applets with a main method.<br />

Thus, you will be able <strong>to</strong> run the program either as an applet or as an application. For<br />

brevity, the main method is not listed in the text.<br />

18.12 How do you pass parameters <strong>to</strong> an applet?<br />

18.13 Where is the getParameter method defined?

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!