תוכנית לדוגמא
התוכנית הבאה תרוץ:
תחת שליטתו של דפדפן בעל יכולת Java (תואם לגירסת JDK 1.1.3 או מאוחרת יותר)
או תחת שליטתה של תוכנית AppletViewer
או תחת שליטת JVM עצמאי.
ההערות מסבירות מה מתבצע. אולם, כיוון שלא כיסינו דבר מן החומר הנוגע לממשק המשתמש הגרפי (Frame וכו'), לא נדון בכך בפרוטרוט בשלב זה. התוכנית נועדה פשוט להבהיר לך את טיבן הכפול של תוכניות applet.
תכנית applet, hello04.java
התוכנית ממחישה שניתן להריץ applets פשוטים באופן עצמאי, וגם בתוך דפדפן או תחת שליטתה של תוכנית AppletViewer.
זהו applet Java היוצר פלט זהה לזה של ה‑applet hello3, למעט העובדה שתוכנית זו מסוגלת לרוץ הן תחת AppletViewer והן באופן עצמאי.
מתודת main משמשת לתמיכת ההרצה של ה‑applet באופן עצמאי.
התוכנית נבדקה תוך שימוש ב‑JDK 1.1.3 תחת Win95.
/*Applet program hello4.java This program illustrates that simple applets can run in a standalone mode as well as inside a browser or under the AppletViewer program. This is a Java applet which produces the same output as the applet named hello3, except that this program is capable of running either under AppletViewer or standalone. A main method is provided to support the running of the applet in the standalone mode. This program was tested using JDK 1.1.3 under Win95 */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class hello4 extends Applet { public void paint(Graphics screen) { screen.drawString("Hello World",50,25); }//end paint() //Provide a main method that can be used to run the // applet in a standalone mode. public static void main(String[] args){ //Create a Frame for the applet to run in Frame myFrame = new Frame( "Copyright 1997, R.G.Baldwin"); myFrame.setSize(300,100); //Instantiate a hello4 applet object. Applet myApplet = new hello4(); //Add the applet object to the Frame object myFrame.add(myApplet); //Make the whole thing visible myFrame.setVisible(true); //This code will terminate the program when the // user clicks the close button on the Frame myFrame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}}); }//end main } //End hello4 class. |
ניתן להשתמש בקובץ html הבא כדי להריץ את התוכנית תחת AppletViewer.
<HTML> <HEAD> <title>Hello World Applet</title> </HEAD> <BODY> <applet code="hello4.class" width=300 height=100> </applet> </BODY> </HTML> |