Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
OBJECT ORIENTED PROGRAMMING Course 9 Loredana STANCIU [email protected] Room B613 APPLETS A program written itt in i th the JJava programming i language that can be included in an HTML page ´ A special kind of Java program that a browser enabled with Java technology can d download l d ffrom th the iinternet t t and d run ´ Embedded inside a web p page g and runs in the context of a browser ´ Extends the Applet class ´ LIFE CYCLE OF AN APPLET ´ ´ ´ ´ init(): i i () intended i t d d ffor whatever h t iinitialization iti li ti iis needed for the applet start(): automatically called after init() and whenever user returns to the page containing the applet after visiting other pages stop(): p() automaticallyy called whenever the user moves away from the page containing applets or to stop p an animation destroy: called when the browser shuts down normally. normally LOADING APPLETS IN A WEB PAGE <applet l t code=AppletWorld.class d l t ld l width="200" height="200"> ´ </applet> ´ appletviewer l t i A l tW ld ht l AppletWorld.html ´ when making g changes g to the applet's pp code while it is loaded in the browser, then recompile the applet and press the "Shift Shift + Reload" button in the browser to load the new version ´ GETTING STARTED WITH APPLETS ´ ´ ´ ´ import i t java.applet.*; j l t * import java.awt.Graphics; public bli class l H ll W ld extends HelloWorld t d Applet A l t { « public void paint(Graphics g) { ² g.drawRect(0, 0 0 0, getSize().width - 1, 1 getSize().height - 1); ² g.drawString("Hello d St i ("H ll world!", ld!" 5, 5 15); 15) « } } GETTING STARTED WITH APPLETS ´ ´ Managed M d and d run b by Java J Plug-in Pl i Extends the functionality of a web browser, allowing applets to be run under Sun's Java(TM) SE Runtime Environment (JRE) rather than the Java Runtime Environment that comes with the web browser CONVERTING APPLICATIONS TO APPLETS An application: A li ti a standalone t d l program consisting of at least one class with a main method. ´ Applets ´ « do not have a main method « several methods are called at different points in the execution of an applet ´ The difference between Java applets and applications lies in how they are run CONVERTING APPLICATIONS TO APPLETS ´ Create C t a subclass b l off java.applet.Applet and override the init method to initialize the applet's resources the same way the main method initializes the application's resources. ´ init might be called more than once and should be designed accordingly. The top-level Panel needs to be added to the applet in init; usually it was added to a Frame in main. OVERRIDING APPLET APPLET’S S METHODS ´ init() « useful for one-time initialization that doesn't take very long « contains the code normally put into a constructor ´ start() ´ every applet that does something after i iti li ti ((exceptt iin di initialization directt response tto user actions) must override the start method ´ either performs the applet's work or (more likely) starts up one or more threads to perform the work OVERRIDING APPLET APPLET’S S METHODS ´ stop() t () « most applets that override start should also override the stop method. « suspend p ´ the applet's pp execution,, so that it doesn't take up system resources when the user isn't viewing g the applet's pp p page g destroy() « available for applets that need to release additional resources. USING THE PAINT METHOD ´ Used to draw the applet's pp representation p within a browser page ´ public void p p paint(Graphics ( p g) { « /*Draw a Rectangle around the applet's display area.*/ « g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); « /*Draw the current string inside the rectangle.*/ « g.drawString(buffer.toString(), 5, 15); } ´ The Graphic class Is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices ´ A Graphics object encapsulates state information needed for the basic rendering operations that Java supports ´ The Graphic class ´ This state information includes the following properties: « The Component p object j on which to draw. « A translation origin for rendering and clipping coordinates. The current clip. The current color. The current font. The current logical g p pixel operation p function ((XOR or Paint). The current XOR alternation color « « « « « The Graphic class ´ All coordinates that appear as arguments to the methods of this Graphics object are considered relative to the translation origin of this Graphics object prior to the invocation off the method. The Graphic class ´ public bli void id t translate(int l t (i t x, int i t y) ) « Translates ´ the origin of the graphics context to the point (x, y) in the current coordinate system public Color g p getColor() « Gets ´ this graphics context's current color. public void setColor(Color c) « Sets this graphics context's current color to the specified ifi d color. l All subsequent b t graphics hi operations using this graphics context use this specified ifi d color. l The Graphic class ´ public Font getFont() « Gets ´ the current font. public bli void id setFont(Font tF t(F t font) f t) « Sets ´ this graphics context's font to the specified font. All subsequent text operations using this graphics context use this font. public void drawLine(int x1, int y1, int x2, int y2) « Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. The Graphic class ´ public bli void id drawRect(int d R t(i t x, int i t y, int width, int height) « Draws ´ the outline of the specified rectangle. The rectangle is drawn using the graphics context's current color. public void clearRect(int x, int y p y, int width, int height) « Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode. The Graphic class ´ p public abstract void drawOval(int x, int y, int width, int height) « Draws ´ the outline of an oval. oval The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments. public abstract void drawArc(int x, int y, y int width, width int height, height int startAngle, int arcAngle) « Draws D th the outline tli off a circular i l or elliptical lli ti l arc covering the specified rectangle. Angles are i t interpreted t d such h th thatt 0 degrees d iis att th the 3 o'clock ' l k position The Graphic class ´ public bli void id drawString(String d St i (St i str, t int x, int y) « ´ Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x (x, y) in this graphics context's coordinate system. public abstract void drawPolygon (int[] xPoints, int[] yPoints, int nPoints) « Draws a closed polygon defined by arrays of x and d y coordinates. di t E Each h pair i off ((x, y)) coordinates di t defines a point. The Color class ´ ´ Used U d encapsulate l t colors l iin th the d default f lt sRGB RGB color l space Predefined values for colors: « BLACK,, BLUE,, CYAN,, DARK GREY,, GREY,, GREEN, LIGHT GREY, MAGENTA, ORANGE, PINK,, RED,, WHITE,, YELLOW,, The Applet class Mustt be M b the th superclass l off any applet l t that th t is i to be embedded in a Web page or viewed by the Java Applet Viewer ´ Provides a standard interface between applets and their environment. ´ More on ´ http://java.sun.com/j2se/1.4.2/docs/api/java/appl et/Applet.html The Applet tag ´ ´ ´ ´ ´ ´ <APPLET « CODEBASE = codebaseURL « ARCHIVE = archiveList « CODE = appletFile ...or... or OBJECT = serializedApplet « ALT = alternateText « NAME = appletInstanceName pp « WIDTH = pixels « HEIGHT = pixels « ALIGN = alignment « VSPACE = pixels HSPACE = pixels > <PARAM NAME = appletAttribute1 VALUE = value> <PARAM NAME = appletAttribute2 VALUE = value> ... alternateHTML </APPLET> The Applet tag ´ CODEBASE = codebaseURL « ´ OPTIONAL attribute specifies the base URL of the applet — the directory that contains the applet's code. If this attribute is not specified, then the document's URL is used. ARCHIVE = archiveList « OPTIONAL attribute describes one or more archives containing classes and other resources that will be "preloaded". The classes are loaded using an instance of an AppletClassLoader with the given CODEBASE. CODEBASE The Applet tag ´ CODE = appletFile pp « ´ REQUIRED attribute gives the name of the file that contains the applet's compiled Applet subclass. This file is relative to the base URL of the applet. The value appletFile can be of the form classname.class or of the f form packagename.classname.class. k l l ALT = alternateText « OPTIONAL attribute specifies any text that should be displayed if the browser understands the APPLET tag but can'tt run Java applets can applets. The Applet tag ´ NAME = appletInstanceName pp « ´ ALT = alternateText « ´ OPTIONAL attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other. OPTIONAL attribute specifies any text that should be displayed if the browser understands the APPLET tag but can't run Java applets. WIDTH = pixels HEIGHT = pixels « REQUIRED attributes give the initial width and height (in pixels) of the applet display area, not counting any windows or dialogs that the applet brings up. The Applet tag ´ ALIGN = alignment g « ´ VSPACE = p pixels HSPACE = p pixels « ´ OPTIONAL attribute specifies the alignment of the applet. The possible values of this attribute are: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom. OPTIONAL attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). <PARAM NAME = appletAttribute1 VALUE = value> « The only way to specify an applet-specific attribute. Applets access their attributes with the getParameter() method. Example — Drawing lines ´ ´ ´ import java.applet.*; import java.awt.*; public class DrawingLines extends Applet { « int i t width, idth height; h i ht « public void init() { ² width = getSize().width; getSize() width; ² height = getSize().height; ² setBackground( Color.black Color black ); } « public void paint( Graphics g ) { ²g g.setColor( ( Color.green g ); ² for ( int i = 0; i < 10; ++i ) { ¹ g.drawLine( width, height, i * width / 10, 0 ); } } } Example — Drawing lines ´ <applet < l t width=300 idth 300 height=300 h i ht 300 code="DrawingLines.class"> </applet> Example — Drawing Other Stuff ´ ´ ´ import java.applet.*; import java.awt.*; public class DrawingLines extends Applet { « int i t width, idth height; h i ht « public void init() { ² width = getSize().width; getSize() width; ² height = getSize().height; ² setBackground( Color.black Color black ); } « public void paint( Graphics g ) { ²g g.setColor( ( Color.red ); ² g.drawRect( 10, 20, 100, 15 ); ² g.setColor( Color.pink ); ² g.fillRect( 240, 160, 40, 110 ); ²… Example — Drawing Other Stuff ²… ² g.setColor( Color.blue ); ² g.drawOval( 50, 225, 100, 50 ); ² g.setColor( tC l ( Color.orange C l ) ); ² g.fillOval( 225, 37, 50, 25 ); ² g.setColor( Color.yellow ); ² g.drawArc( g drawArc( 10, 110, 80, 80, 90, 180 ); ² g.setColor( Color.cyan ); ²g g.fillArc( ( 140, , 40, , 120, , 120, , 90, , 45 ); ²… Example — Drawing Other Stuff ²… ² g.setColor( Color.magenta ); ² g.fillArc( 150, 150, 100, 100, 90, 90 ); ² g.setColor( tC l ( Color.black C l bl k ); ) ² g.fillArc( 160, 160, 80, 80, 90, 90 ); ² g.setColor( Color.green ); ² g.drawString( g drawString( "Groovy!", Groovy! , 50, 150 ); « ´ } } Example — Drawing Other Stuff ´ The output: Example — Mouse Input ´ ´ ´ ´ ´ ´ import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; java util *; public class Mouse3 extends Applet implements MouseMotionListener { « int width, height; « Vector listOfPositions; « public bli void id i init() it() { ² width = getSize().width; height = getSize().height; g g setBackground( g Color.black ); ² listOfPositions = new Vector(); ² addMouseMotionListener( this ); } … Example — Mouse Input « « « public void mouseMoved( MouseEvent e ) { ² if ( listOfPositions.size() li tOfP iti i () > >= 50 ) ¹ listOfPositions.removeElementAt( 0 ); ² repaint(); ² e.consume();} public void mouseDragged( MouseEvent e ) { } public void paint( Graphics g ) { ² g.setColor( Color.white ); ² for f ( int i t j = 1 1; j < listOfPositions.size(); li tOfP iti i () ++j ) { ¹ Point A = (Point)(listOfPositions.elementAt(j1)); ¹ Point B = (Point)(listOfPositions elementAt(j)); (Point)(listOfPositions.elementAt(j)); ¹ g.drawLine( A.x, A.y, B.x, B.y ); } } } Example — Keyboard Input ´ ´ ´ ´ import java.applet.*; i import t j java.awt.*; t * import java.awt.event.*; public class Keyboard1 extends Applet implements KeyListener, MouseListener { « int width, height; int x, y; String s = ""; « public void init() { ² width = getSize().width; height = getSize().height; ² setBackground( Color.black ); ² x = width/2; y = height/2; ² addKeyListener( this ); ² addMouseListener( this ); ²} ²… Example — Keyboard Input « « « « « « « « « … public bli void id keyPressed( k P d( KeyEvent K E t e ) { } public void keyReleased( KeyEvent e ) { } public void keyTyped( KeyEvent e ) { ² char c = e.getKeyChar(); ² if ( c != KeyEvent.CHAR_UNDEFINED ) { ¹ s = s + c; ¹ repaint(); ¹ e.consume(); () } } public void mouseEntered( MouseEvent e ) { } public pub c void o d mouseExited( ouse ted( MouseEvent ouse e t e ) { } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } … Example — Keyboard Input « « « ´ } … public bli void id mouseClicked( Cli k d( MouseEvent M E t e ) { ² x = e.getX(); y = e.getY(); ² s = ""; ; ² repaint(); ² e.consume(); } public void paint( Graphics g ) { ² g.setColor( Color.gray ); ² g.drawLine( d Li ( x, y, x, y-10 10 ) ); ² g.drawLine( x, y, x+10, y ); ² g.setCo g.setColor( o ( Co Color.green o .g ee ); ² g.drawString( s, x, y ); } Example — Threads ´ ´ ´ ´ ´ import java.applet.*; i import t j java.awt.*; t * import java.util.*; import java.text. java.text.*; ; public class Clock extends Applet implements Runnable { « int width, height; « Thread t = null; « boolean threadSuspended; « int hours=0, minutes=0, seconds=0; « String timeString = ""; « public void init() { ² width = getSize().width; height = getSize().height; tSi () h i ht ² setBackground( Color.black ); } Example — Threads « « … public bli void id start() t t() { ² if ( t == null ) { ¹ t = new Thread( this ); ¹ t.setPriority( Thread.MIN_PRIORITY ); ¹ threadSuspended = false; ¹ t.start(); } ² else { ¹ if ( threadSuspended th dS d d ) { ° threadSuspended = false; « sy synchronized( c o ed( t this s ) { notify(); ot y(); } ° } } } ² public void stop() { threadSuspended = true; } ²… Example — Threads « « … public bli void id run() () { ² try { ² while (true) { ¹ Calendar cal = Calendar.getInstance(); ¹ hours = cal.get( Calendar.HOUR_OF_DAY ); ¹ if ( hours > 12 ) hours -= 12; ¹ minutes = cal.get( Calendar.MINUTE ); ¹ seconds d = cal.get( l t( Calendar.SECOND C l d SECOND ); ) ¹ SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() ); ¹ Date date = cal.getTime(); ¹ timeString ti St i = formatter.format( f tt f t( d date t ) ); ²… Example — Threads « … « if ( threadSuspended th dS d d ) { ° synchronized( this ) { « while ( threadSuspended ) { wait(); } ° } } ¹ repaint(); ¹ t.sleep( 1000 );} } ² catch (InterruptedException e) { } } void id drawHand( d H d( d double bl angle, l i t radius, int di G Graphics hi g ) { ² angle -= 0.5 * Math.PI; ² int x = (int)( radius*Math.cos(angle) ); ² int y = (int)( radius*Math.sin(angle) ); ² g.drawLine( width/2, / height/2, / width/2 / + x, height/2 + y ); } … ¹ « Example — Threads « « « … void drawWedge( double angle, int radius, Graphics g ) { ² angle -= 0.5 * Math.PI; ² int x = (int)( radius*Math.cos(angle) ); ² int i t y = (int)( (i t)( radius*Math.sin(angle) di * th i ( l ) ) ); ² angle += 2*Math.PI/3; ² int x2 = (int)( 5*Math.cos(angle) ); ² int y2 = (int)( 5*Math.sin(angle) ); ² angle += 2*Math.PI/3; ² int x3 = (int)( 5*Math.cos(angle) 5*Math cos(angle) ); ² int y3 = (int)( 5*Math.sin(angle) ); ² g.drawLine( width/2+x2, height/2+y2, width/2 + x, h i h /2 + y ) height/2 ); ² g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y ); ² g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 ); } … Example — Threads « « ´ } … public void paint( Graphics g ) { ² g.setColor( Color.gray ); ² drawWedge( 2*Math.PI * hours / 12, width/5, g ); ² drawWedge( 2*Math.PI * minutes / 60, width/3, g ); ² drawHand( 2*Math.PI * seconds / 60, width/2, g ); ² g.setColor( Color.white ); ² g.drawString( timeString, 10, height-10 ); } REFERENCES ´ ´ http://java.sun.com/docs/books/tutorial/deployme h //j /d /b k / i l/d l nt/applet/index.html http://www.dgp.toronto.edu/~mjmcguff/learn/java/