13. Applets Χειμερινό εξάμηνο 2012 Πέτρος Κωμοδρόμος komodromos@ucy.ac.cy http://www.eng.ucy.ac.cy/petros 1
Θέματα Εισαγωγή στα applets Applets και Applications Διαθέσιμα applets με το JDK Δημιουργία applets Χρήση απλού HyperText Markup Language (HTML) εγγράφου για να φορτωθεί και εκτελεστεί ένα applet σε ένα αποδέκτη applet Εκτέλεση ενός applet στον appletviewer Εκτέλεση ενός applet σε ένα web browser Μέθοδοι που καλούνται αυτόματα από ένα αποδέκτη applet κατά τη ζωή του applet (Applet Life-Cycle Methods) Αρχικοποιώντας μία μεταβλητή με τη μέθοδο init Μοντέλο ασφαλείας sandbox Διαδίκτυο και πόροι πλεγμάτων (internet and web resources) 2
Εισαγωγή στα Applets Ειδικά προγράμματα Java τα οποία μπορούν να ενσωματωθούν σε αρχεία HyperText Markup Language (HTML) και να εκτελεστούν σε κάποιο browser Ένας browser που εκτελεί ένα applet είναι γνωστός σαν αποδέκτης του applet (applet container) Τα applets παλαιότερα βασίζονταν στην τάξη Applet (java.applet.applet) Τώρα πλέον για τα applets χρησιμοποιείται η τάξη JApplet του Swing (javax.swing.japplet) Η τάξη JApplet έχει default layout manager το Flowlayout Για λόγους ασφαλείας τα applets έχουν συνήθως αυστηρούς περιορισμούς στη πρόσβαση πόρων ενός συστήματος 3
Java Application MyJavaApplication.java public class MyJavaApplication public static void main ( String args[ ]) System.out.println("Java Application..."); > javac MyJavaApplication.java 4
Java Applet MyJavaApplet.java import javax.swing.japplet; import java.awt.*; public class MyJavaApplet extends JApplet public void paint(graphics g) super.paint(g); g.setcolor(color.blue); g.drawrect(1,1,getwidth()-2,getheight()-2); g.drawstring("my Java Applet", 100, 50); > javac MyJavaApplet.java 5
Ενσωμάτωση ενός Applet σε ιστοσελίδα myjavaapplet.html: <HTML> <HEAD> <TITLE> A simple program to run a Java Applet</TITLE> </HEAD> <BODY> Here the class myapplet is loaded: <P> <APPLET CODE= "MyJavaApplet.class" WIDTH=200 HEIGHT=100 align=center> </APPLET> </BODY> </HTML> 6
Εκτέλεση Applet Πρώτα με το Appletviewer: > appletviewer myjavaapplet.html Και στη συνέχεια με όλους τους Browsers στους οποίους μπορεί να χρησιμοποιηθεί το Applet: o o o o o Microsoft Explorer Netscape Opera Mozila Firefox κ.λπ. 7
Java Application με συστατικό GUI import javax.swing.*; MyJavaApplicationGUI.java public class MyJavaApplicationGUI public static void main(string args[]) javax.swing.swingutilities.invokelater(new Runnable() public void run() createandshowjframe(); ); static void createandshowjframe() JFrame jfr = new JFrame("MyJavaApplicationGUI"); JLabel label = new JLabel("Java Application with GUI..."); jfr.add(label); jfr.setbounds(100,50,500,150); jfr.setdefaultcloseoperation(jframe.exit_on_close); jfr.setvisible(true); 8
Συνδυασμός Java Application και Java Applet import java.awt.*; import javax.swing.*; AppletApplicationCombo.java public class AppletApplicationCombo extends JApplet private JLabel label; public static void main(string args[]) javax.swing.swingutilities.invokelater(new Runnable() public void run() JFrame myframe = new JFrame("MyJavaApplicationGUI"); JApplet myapplet = new MyApplet(); myapplet.init(); myapplet.start(); myframe.setcontentpane(myapplet.getcontentpane()); myframe.setbounds(100,50,500,150); myframe.setdefaultlookandfeeldecorated(true); myframe.setdefaultcloseoperation(jframe.exit_on_close); myframe.setvisible(true); ); 9
AppletApplicationCombo.java public void init() label = new JLabel("Java Application with GUI..."); add(label); <HTML> <HEAD> <TITLE> Java Applet and Application Combo </TITLE> </HEAD> <BODY> Class MyApplet <P> <APPLET CODE="AppletApplicationCombo.class" WIDTH=200 HEIGHT=100 align=center> </APPLET> </BODY> </HTML> 10
AppletApplicationCombo.class: Εκτέλεση σαν Application 11
AppletApplicationCombo.class: Εκτέλεση σαν Applet 12
Διαθέσιμα Applets με το JDK: /jdk1.5.0/demo Example Description Animator ArcTest BarChart Blink CardTest Clock DitherTest DrawTest Fractal Performs one of four separate animations. Demonstrates drawing arcs. You can interact with the applet to change attributes of the arc that is displayed. Draws a simple bar chart. Displays blinking text in different colors. Demonstrates several GUI components and layouts. Draws a clock with rotating hands, the current date and the current time. The clock updates once per second. Demonstrates drawing with a graphics technique known as dithering that allows gradual transformation from one color to another. Allows the user mouse to draw lines and points in different colors by dragging the mouse. Draws a fractal. Fractals typically require complex calculations to determine how they are displayed. GraphicsTest Draws shapes to illustrate graphics capabilities. 13
Example Description GraphLayout Draws a graph consisting of many nodes (represented as rectangles) connected by lines. Drag a node to see the other nodes in the graph adjust on the screen and demonstrate complex graphical interactions. ImageMap Demonstrates an image with hot spots. Positioning the mouse pointer over certain areas of the image highlights the area and displays a message in the lower-left corner of the applet container window. Position over the mouth in the image to hear the applet say hi. JumpingBox Moves a rectangle randomly around the screen. Try to catch it by clicking it with the mouse! 14
Example Description MoleculeViewer Presents a three-dimensional view of several chemical molecules. Drag the mouse to view the molecule from different angles. NervousText SimpleGraph SortDemo SpreadSheet TicTacToe WireFrame Draws text that jumps around the applet. Draws a complex curve. Compares three sorting techniques. Sorting (described in Chapter 16) arranges information in order like alphabetizing words. When you execute this example from a command window, three appletviewer windows appear. When you execute this example in a browser, the three demos appear side-by-side. Click in each demo to start the sort. Note that the sorts all operate at different speeds. Demonstrates a simple spreadsheet of rows and columns. Allows the user to play Tic-Tac-Toe against the computer. Draws a three-dimensional shape as a wire frame. Drag the mouse to view the shape from different angles. 15
Μενού Applet στον appletviewer Reload the applet to execute it again. Select Quit to terminate the appletviewer. 16
jdk1.5.0_06\demo\jfc\java2d 17
Δημιουργία ενός απλού Java Applet Ένας αποδέκτης applet (δηλαδή ένα applet container) μπορεί να δημιουργήσει μόνο αντικείμενα τάξεων τα οποία είναι υποτάξεις της τάξης JApplet (ή της τάξης Applet) και να είναι public. Η κάθε τάξη για applets με το Swing κληρονομεί τις εξής μεθόδους από την τάξη JApplet, τις οποίες μπορεί να επαναορίσει: init start paint stop destroy Όταν ένας αποδέκτης applet (ένα applet container) φορτώσει μία τάξη applet, δημιουργεί ένα αντικείμενο εκείνης της τάξης και ακολούθως καλεί τις βασικές μεθόδους με τη σειρά: init - start paint stop - destroy 18
Ιεραρχία JApplet 19
Μέθοδοι ενός Applet που εκτελούνται σε συγκεκριμένες στιγμές init: Καλείται από τον browser ή τον Appletviewer μία φορά όταν το applet φορτωθεί ή επαναφορτωθεί στη μνήμη για εκτέλεση start: Καλείται, αφού εκτελεστεί η init, για να κάνει ότι απαιτείται όταν το applet γίνει ορατό ώστε να ξεκινήσει η εκτέλεση του paint: Καλείται όποτε το applet σχεδιάζεται ή επανασχεδιάζεται stop: Καλείται για να σταματήσει ότι ενέργειες κάνει το applet όταν δεν είναι πλέον ορατό (π.χ. όταν εικονοποιείται ή όταν ο χρήστης επισκέπτεται άλλη ιστοσελίδα) destroy: Καλείται πριν το applet καταστραφεί και για να γίνει μία τελική απελευθέρωση οποιοδήποτε πόρων που έχει πάρει το applet 20
1 // Fig. 20.6: WelcomeApplet.java 2 // A first applet in Java. 3 import java.awt.graphics; // program uses class Graphics 4 import javax.swing.japplet; // program uses class JApplet 5 6 public class WelcomeApplet extends JApplet 7 8 // draw text on applet s background 9 public void paint( Graphics g ) 10 11 // call superclass version of method paint 12 super.paint( g ); 13 14 // draw a String at x-coordinate 25 and y-coordinate 25 15 g.drawstring( "Welcome to Java Programming!", 25, 25 ); 16 // end method paint 17 // end class WelcomeApplet Import Graphics and JApplet Class WelcomeApplet extends class JApplet Call the superclass version of method paint Use Graphics method drawstring to draw Welcome to Java Programming! 21
1 <html> 2 <applet code = "WelcomeApplet.class" width = "300" height = "45"> 3 </applet> 4 </html> Specify an applet element Applet element attributes Εκτέλεση του WelcomeApplet σε Appletviewer y-axis x-axis Upper-left corner of drawing area is location (0, 0). Drawing area extends from below the Applet menu to above the status bar. x- coordinates increase from left to right. y-coordinates increase from top to bottom. Applet menu Status bar mimics what would be displayed in the browser s status bar as the applet loads and begins executing. Pixel coordinates (25, 25) at which the string is displayed 22
Εκτέλεση του WelcomeApplet σε Microsoft Internet Explorer Upper-left corner of drawing area Pixel coordinate (25, 25) Status bar 23
Παρατηρήσεις Για να παρουσιάζεται καλά ένα Applet στους περισσότερους browsers είναι καλύτερα οι διαστάσεις του να μήν υπερβαίνουν τα 1024 pixels πλάτος 768 pixels ύψος Κατά τη διάρκεια της ανάπτυξης ενός Applet είναι προτιμότερο να ελέγχεται πρώτα στον Appletviewer και ακολούθως σε όλους τους Web browsers όπου πιθανόν να χρησιμοποιηθεί Ένα μύνημα MissingResourceException κατά την φόρτωση ενός Applet στον appletviewer ή σε ένα browser, πιθανόν να οφείλεται σε κάποιο λάθος στο στοιχείο <applet> μέσα στο αρχείο HTML. Μέσα στη μέθοδο init πρέπει να μπαίνουν εντολές που εκτελούνται μόνο μία φορά όταν το applet αρχικοποιείται. 24
JApplet life cycle methods Method When the method is called and its purpose public void init() Called once by the applet container when an applet is loaded for execution. This method initializes an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 20, Multimedia: Applets and Applications) and creating threads (see Chapter 23, Multithreading). public void start() Called by the applet container after method init completes execution. In addition, if the user browses to another Web site and later returns to the applet s HTML page, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the applet s HTML page is revisited. Actions performed here might include starting an animation (see Chapter 21) or starting other threads of execution (see Chapter 23). 25
JApplet life cycle methods Method When the method is called and its purpose public void paint( Graphics g ) Called by the applet container after methods init and start. Method paint is also called when the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. public void stop() This method is called by the applet container when the user leaves the applet s Web page by browsing to another Web page. Since it is possible that the user might return to the Web page containing the applet, method stop performs tasks that might be required to suspend the applet s execution, so that the applet does not use computer processing time when it is not displayed on the screen. Typical actions performed here would stop the execution of animations and threads. 26
JApplet life cycle methods Method When the method is called and its purpose public void destroy() This method is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows and may also occur at the browser s discretion when the user has browsed to other Web pages. The method performs any tasks that are required to clean up resources allocated to the applet. 27
Example with life cycle methods of a Java Applet MyAppletLifeCycle.java import javax.swing.*; import java.awt.*; public class MyAppletLifeCycle extends JApplet public void init() JOptionPane.showMessageDialog(null,"Executing method init()"); public void start() JOptionPane.showMessageDialog(null,"Executing method start()"); 28
MyAppletLifeCycle.java public void paint(graphics g) super.paint(g); JOptionPane.showMessageDialog(null,"Executing method paint()"); g.setcolor(color.blue); g.drawrect(1,1,getwidth()-2,getheight()-2); g.drawstring("my Java Applet", 100, 50); public void stop() JOptionPane.showMessageDialog(null,"Executing method stop()"); public void destroy() JOptionPane.showMessageDialog(null,"Executing method destroy()"); 29
MyAppletLifeCycle.html 30
31
1 // Fig. 20.10: AdditionApplet.java 2 // Adding two floating-point numbers. 3 import java.awt.graphics; // program uses class Graphics 4 import javax.swing.japplet; // program uses class JApplet 5 import javax.swing.joptionpane; // program uses class JOptionPane 6 7 public class AdditionApplet extends JApplet 8 9 private double sum; // sum of values entered by user 10 11 // initialize applet by obtaining values from user 12 public void init() 13 14 String firstnumber; // first string entered by user 15 String secondnumber; // second string entered by user 16 17 double number1; // first number to add 18 double number2; // second number to add 19 20 // obtain first number from user 21 firstnumber = JOptionPane.showInputDialog( 22 "Enter first floating-point value" ); 23 24 // obtain second number from user 25 secondnumber = JOptionPane.showInputDialog( 26 "Enter second floating-point value" ); 27 Declare instance variable sum of type double init method called once when the container loads this applet 32
28 // convert numbers from type String to type double 29 number1 = Double.parseDouble( firstnumber ); 30 number2 = Double.parseDouble( secondnumber ); 31 32 sum = number1 + number2; // add numbers 33 // end method init 34 35 // draw results in a rectangle on applet s background 36 public void paint( Graphics g ) 37 38 super.paint( g ); // call superclass version of method paint 39 40 // draw rectangle starting from (15, 10) that is 270 41 // pixels wide and 20 pixels tall 42 g.drawrect( 15, 10, 270, 20 ); 43 44 // draw results as a String at (25, 25) 45 g.drawstring( "The sum is " + sum, 25, 25 ); 46 // end method paint 47 // end class AdditionApplet Sum the values and assign the result to instance variable sum Call drawstring to display sum 33
1 <html> 2 <applet code = "AdditionApplet.class" width = "300" height = "65"> 3 </applet> 4 </html> 34
Example with life cycle methods of a Java Applet import javax.swing.*; import java.awt.*; public class MyAppletLifeCycle2 extends JApplet private String labeltext="my Java Applet: "; public void init() labeltext = labeltext + "...init()"; public void start() labeltext = labeltext + "...start()"; MyAppletLifeCycle2.java 35
public void paint(graphics g) super.paint(g); labeltext = labeltext + "...paint()"; g.setcolor(color.blue); g.drawrect(1,1,getwidth()-2,getheight()-2); g.drawstring(labeltext, 100, 50); public void stop() labeltext = labeltext + "...stop()"; MyAppletLifeCycle2.java public void destroy() labeltext = labeltext + "...destroy()"; 36
MyAppletLifeCycle2.html 37
38
Διαχείριση συμβάντων με εσωτερικές κλάσεις import javax.swing.*; import java.awt.event.*; public class TestMyJFrame4 public static void main(string args[]) javax.swing.swingutilities.invokelater(new Runnable() public void run() new MyJFrame4("Testing MyJFrame4 Class"); ); Java Application: TestMyJFrame4.java 39
class MyJFrame4 extends JFrame private JPanel panel; private JLabel label1; private int numberclicks=0; private JButton button1; MyJFrame4(String s) super(s); panel = new JPanel(); panel.setborder(borderfactory.createemptyborder(40, 20, 20, 30)); label1 = new JLabel(); setlabel(); panel.add(label1); button1 = new JButton("Click me!!!"); button1.addactionlistener(new MyInnerEventHandler()); panel.add(button1); add(panel); setbounds(100,50,500,150); setdefaultlookandfeeldecorated(true); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); 40
void setlabel() label1.settext("number of button clicks = " + numberclicks); // Orismos MyButtonEventHandler san inner class private class MyInnerEventHandler implements ActionListener public void actionperformed(actionevent ae) if(ae.getsource() == button1) numberclicks++; setlabel(); 41
Υλοποίηση του ίδιου προγράμματος σαν Applet import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TestMyApplet4 extends JApplet private JPanel panel; private JLabel label1; private int numberclicks; private JButton button1; Java Applet: TestMyApplet4.java public void init() panel = new JPanel(); numberclicks=0; label1 = new JLabel(); setlabel(); panel.add(label1); button1 = new JButton("Click me!!!"); button1.addactionlistener(new MyInnerEventHandler()); panel.add(button1); add(panel); 42
public void start() setvisible(true); public void paint(graphics g) super.paint(g); setlabel(); Java Applet: TestMyApplet4.java void setlabel() label1.settext("number of button clicks = " + numberclicks); private class MyInnerEventHandler implements ActionListener public void actionperformed(actionevent ae) if(ae.getsource() == button1) numberclicks++; setlabel(); 43
TestMyApplet4.html 44
Δυνατότητες των Applets Τα applets μπορούν να τρέξουν μέσα σε ένα web-browser Κληρονομούν όλες τις δυνατότητες για γραφικά και διαχείριση συμβάντων Ένα applet μπορεί να κάνει καμία διαδικτυακή σύνδεση με τον εξυπηρετητή από όπου έχει προέλθει Ένα applet μπορεί να καλέσει public μεθόδους ενός άλλου applet. Τα applets που φορτώνονται από τοπικό δίσκο δεν έχουν τους επόμενους περιορισμούς Μπορούν να παρουσιάσου μηνύματα στο status line με τη μέθοδο showstatus() 45
Ασφάλεια και Applets: Sandbox Security Model Ο κώδικας που εκτελείται στο sandbox δεν επιτρέπεται να κάνει οτιδήποτε έξω από αυτό Δεν επιτρέπεται σε ένα applet το οποίο έχει κατεβεί στον Η/Υ από το διαδίκτυο να έχει πρόσβαση σε τοπικούς πόρους (π.χ. αρχεία) Δεν επιτρέπεται σε ένα applet να ξεκινήσει οποιοδήποτε πρόγραμμα Δεν επιτρέπεται σε ένα applet πρόσβαση σε κάποιες ιδιότητες του Η/Υ Ένα applet δεν μπορεί να κάνει καμία διαδικτυακή σύνδεση εκτός με τον εξυπηρετητή από όπου έχει προέλθει Για περισσότερες πληροφορίες σχετικά με την ασφάλεια και τα applets: developer.java.sun.com/developer/technicalarticles/security/signed Για περισσότερες πληροφορίες σχετικά με την ασφάλεια της Java 2 java.sun.com/j2se/5.0/docs/guide/security/spec/security-spec.doc1.html JARS (Java Applet Rating Service) www.jars.com 46
Φόρτωση ιστοσελίδας με Applet import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import java.net.*; Java Applet: TestMyApplet5.java public class TestMyApplet5 extends JApplet private JButton button1; public void init() button1 = new JButton("Click me!!!"); button1.addactionlistener(new ActionListener() public void actionperformed(actionevent ae) if(ae.getsource() == button1) AppletContext appletcontext = URL url=null ; getappletcontext(); 47
try url = new URL("http://www.eng.ucy.ac.cy/Archimedes"); appletcontext.showdocument(url); catch (MalformedURLException e) System.err.println("Malformed URL: " + url); ); add(button1); public void start() setvisible(true); 48
TestMyApplet5.html 49
50
Πρόσβαση σε κάποια στοιχεία του Η/Υ import javax.swing.japplet; import java.awt.*; Java Applet: MyJavaApplet3.java public class MyJavaApplet3 extends JApplet public void paint(graphics g) super.paint(g); g.setcolor(color.blue); g.drawrect(1,1,getwidth()-2, getheight()-2); g.drawstring("java Version: " + System.getProperty("java.version"), 20, 50); g.drawstring("operating System: " + System.getProperty("os.name"), 20, 100); g.drawstring("file Separator " + System.getProperty("file.separator"), 20, 150); 51
52