SlideShare a Scribd company logo
Java Applets
Introducing Applets Applets Java programs called from within another application Frequently run from a Web page Display as rectangular area Can respond to user-initiated events Behaviors come from Java class named  JApplet Steps to write an applet Set up layout for applet Create components and add them to applet
Applets An  applet  is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page to tell the browser about the applet You don’t need to supply a  main  method; the browser does that When you write an applet, you are writing only  part  of a program  You supply certain methods that the browser calls For security reasons, applets run in a  sandbox : they have no access to the client’s file system
What an applet is You write an applet by extending the class  JApplet   JApplet  is just a class like any other; you can even use it in applications if you want When you write an applet, you are only writing  part  of a program; the browser supplies the  main  method Once you understand how applets work, you can write a program that function either as an applet or as an application—just write a  main  method that calls the right methods at the right time Such programs have the ugly name “ appletcations ”
The genealogy of  JApplet java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet | +----javax.swing.JApplet
The simplest possible applet import javax.swing.JApplet; public class TrivialApplet extends JApplet { } <applet   code=&quot;TrivialApplet.class&quot;   width=&quot;150&quot;   height=&quot;100&quot;> </applet> TrivialApplet.java TrivialApplet.html
The simplest reasonable applet import java.awt.*; import javax.swing.JApplet; public class HelloWorld extends JApplet {   public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 30, 30); } }
What are the disadvantages of applets? Applets can’t run any local executable programs Applets can’t with any host other than the originating server Applets can’t read/write to local computer’s file system
What are the disadvantages of applets? (Cont’d) Applets can’t find any information about the local computer All java-created pop-up windows carry a warning message Stability depends on stability of the client’s web server Performance directly depend on client’s machine
What are the advantages of applets?  Automatically integrated with HTML; hence, resolved virtually all installation issues. Can be accessed from various platforms and various java-enabled web browsers. Can provide dynamic, graphics capabilities and visualizations Implemented in Java, an easy-to-learn OO programming language
What are the advantages of applets? (Cont’d) Alternative to HTML GUI design  Safe! Because of the security built into the core Java language and the applet structure, you don’t have to worry about bad code causing damage to someone’s system  Can be launched as a standalone web application independent of the host web server
Java Applets Can not Applets  are programs designed to run as part of a  Web Page  (Applet = little application). Applets are similar to normal Java Applications but have extra security features to prevent a downloaded Applet damaging your computer or transmitting information from it. For instance an Applet cannot: Access local files Delete local files Run another program Find out your name Connect to another host
Running a Java Applet You write Java code using an editor javac MyApp.java appletviewer MyApp.html Text Editor You save the file with a  .java  extension You run the Java compiler ' javac ' You can view the applet with the command ' appletviewer ' This creates a file of  bytecode  with a  .class  extension Web Browser You write a web page in html using an editor You can view the web page from a web browser You save the file with a  .html  extension Java code: MyApp.java Bytecode: MyApp.class Window Web page: MyApp.html Text Editor
Creating an Applet    Open &quot; Notepad &quot; (Start    Programs    Other    Notepad)    Type this in:     Save As  &quot;Greetings.java&quot; (Put the &quot; &quot; round the name otherwise it adds .txt to the end!)    Open a  DOS  Window (Start    MS-DOS Prompt)    Type  javac Greetings.java G:\> javac Greetings.java G:\> If it gives an error check you typed it in  exactly  right. import java.awt.*; import java.applet.Applet; public class Greetings extends Applet { public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 50, 50); }  }    If you type  dir Greetings.*  you should see  Greetings.java  and  Greetings.class
Creating the Web Page In order to run an applet you have to embed it in a web page using a special  <applet>  tag e.g: <applet code=&quot;name.class&quot; width=www height=hhh></applet> <html> <head> <title>Greetings Applet</title> </head> <body> <applet code=&quot;Greetings.class&quot; width=300 height=200 ></applet> </body> </html> Using Notepad type in the following and save it as  &quot;Greetings.html&quot; : Size of the applet in pixels
Running the Program G:\> appletviewer Greetings.html In the DOS window type  appletviewer Greetings.html You should see something like this:
Running in a Web Browser In  Netscape  go to the  File  menu then  Open Page ... Press  Choose File... Find your file  Greetings  with the Netscape symbol alongside it (Greetings.html) - click on it and press  Open  (or double click on it) Back in the Open Page dialog press  Open You should see something like: Title Your greeting Message
What does it mean? import java.awt.*; import java.applet.Applet; public class Greetings extends Applet { public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 50, 50); }  } These 2 lines tell the computer to include ( import ) two standard libraries  awt  (Abstract Window Toolkit) and  applet . This line tells the computer to display some text ( a string) on the screen. This line announces that the program ( class ) can be run by anyone ( public ), is called  Greetings  and is an  Applet . This line declares what follows in the { } as a method called paint.  This is where it is displayed in pixels across and down from the top left hand corner This is what is displayed
General Form of an Applet  New applets are created by extending the  Applet  class contained in the  java . applet  package. Also, the package  java.awt  is needed for the graphical interface of the applet. In general, an applet program would look like the following: import java.applet.*; import java.awt.*; public class AppletName extends Applet { .  .  . }
General Form of an Applet  (cont’d) An applet overrides a set of methods in the class Applet to implement its functionality. These methods are used as an interface with the browser or the applet viewer. An applet does not need to override those methods it does not use.  The following lists the most important methods that are usually used: import java.applet.*; import java.awt.*; public class AppletName extends Applet { public  void  init (){   .  .  .   }   public  void  start (){   .  .  .   }   public  void  stop (){   .  .  .   }   public  void  destroy (){   .  .  .}   public  void  paint (Graphics  g ){   .  .  .} }
Applet Initialization and Termination When an applet begins, the browser calls the following methods, in this sequence:  init() ,  start() . Every time the applet is redrawn, the method  paint()  is called. When an applet is terminated, the following sequence of methods is invoked:  stop() ,  destroy(). Called just before the applet is terminated. Your applet should override this method if it needs to perform any  cleanup  prior to its destruction.   destroy() Called to suspend execution of the applet. Once stopped, an applet is restarted when the execution environment calls  start() .   stop() Called by the execution environment when an applet should start or resume execution. It is automatically called after  init()   when an applet first begins.   start() Applets do not usually have  main  method; instead they have the  init()  method  that, like  main() , is invoked by the execution environment.  It is the first method called for any applet . It is called  only  once   during the run-time of an applet. init() Comment Method
Applet methods public void init () public void start () public void stop () public void destroy () public void paint (Graphics) Also: public void repaint() public void update (Graphics) public void showStatus(String) public String getParameter(String)
public void init ( ) init()  is the first method to execute init()  is  an ideal place to initialize variables init()  is the best place to define the GUI Components (buttons, text fields, checkboxes, etc.), lay them out, and add listeners to them Almost every applet you ever write will have an  init( )  method
start( ) ,  stop( )  and  destroy( ) start()  and  stop( )  are used when the Applet is doing time-consuming calculations that you don’t want to continue when the page is not in front public void start()  is called: Right after  init( ) Each time the page is loaded and restarted public void stop( )  is called: When the browser leaves the page Just before  destroy( ) public void destroy( )  is called after  stop( ) Use  destroy()  to explicitly release system resources (like threads) System resources are usually released automatically
Methods are called in this order init  and  destroy  are only called once each start  and  stop  are called whenever the browser enters and leaves the page do some work   is code called by your  listeners paint  is called when the applet needs to be repainted init() start() stop() destroy() do some work
public void  paint(Graphics g) Needed if you do any drawing or painting other than just using standard GUI  Component s Any painting you want to do should be done here, or in a method you call from here Painting that you do in other methods may  or may not  happen Never call  paint( Graphics ) , call   repaint( )
repaint( ) Call  repaint( )  when you have changed something and want your changes to show up on the screen You do  not  need to call  repaint()  when something in Java’s own components (Buttons, TextFields, etc.) You  do  need to call  repaint()   after drawing commands ( drawRect(...) ,  fillRect(...) ,  drawString(...) , etc.) repaint( )  is a  request --it might not happen When you call  repaint( ) ,  Java schedules a call to  update(Graphics  g )
update( ) When you call  repaint( ) ,  Java schedules a call to  update(Graphics g) Here's what  update  does: public void update(Graphics g) {   // Fills applet with background color, then   paint(g); }
The paint() method The  paint()  method is called by the execution environment (i.e. the browser) each time the applet has to be redrawn. The inherited paint() method is empty. In order to draw anything on the applet, this method must be overridden. paint() method takes an object of class  Graphics  as an input argument, which is passed by the execution environment. public  void  paint(Graphics g){ .  .  . }   This Graphics object represents a drawing area. It has methods to draw strings and many shapes. Also, it can manipulate fonts and colors.
The Graphics Object   A Graphics object has a coordinate system that is illustrated below: Anything that is drawn on the Graphics object, appears on the applet. Some of the drawing methods of the Graphics object are: drawString() drawLine() drawRect() drawOval() (0,0) x y
Displaying Strings Using the Graphics Object To display a string on the Graphics object, the method  drawString()  can be used. It has the following arguments: void drawString( String str, int x, int y) str  is the string to be displayed,  x  and  y  are the coordinates of the top left point of the string. For example, the following applet displays the string “Hello World!!” starting at the point (50,25). Its file name must be  HelloApplet.java. import java.applet.*; import java.awt.*; public class HelloApplet extends Applet { public void paint(Graphics g) {  // overriding paint() method g.drawString(&quot;Hello world!&quot;, 50, 25); } }
Placing an Applet in a Web Page Recall that web pages are written in HTML. HTML language describes the appearance of a page using  tags . For example,  <html>  is a tag. Another tag is  <body> . Some tags have  a closing tag .  For example,  <html>  is closed by  </html> . HTML is based on text, just like Java. You can use any editor (like Notepad or JCreator) to write HTML files. HTML files should have the extension HTML, like  (first.html).  All HTML pages should look like: <html> <body> The body of the html page… write whatever you like here. </body> </html>
Placing an Applet in a Web Page  (cont’d)   To place an applet in a web page, the  <applet>  tag is used in the body of an HTML page as follows: < applet   code =“HelloApplet.class”  width =600  height =100> </ applet > The parts in  green  are called  attributes . The applet tag has three  mandatory  (non-optional) attributes: code:  the name of the class file of the applet. width:  the width of the applet, in pixels. height:  the height of the applet, in pixels. If the class file is not at the same folder as the HTML page, the  codebase  attribute is used to indicate the location of the class file  relative to  the directory that has the HTML page. < applet   code =“HelloApplet.class”  codebase =“app\”  width =600  height =100> </ applet >
Colors The class  Color  of  java . awt  package is used to define Color objects. All colors can be specified as a mix of  three primary colors : red, green, and blue. A particular color can be specified by three integers, each between 0 and 255, or by three float values, each between 0.0 and 1.0. The class Color has some pre-defined colors that are commonly used. 255, 255, 0 1.0F,  1.0F,  0.0F Color.yellow 255, 255, 255 1.0F,  1.0F,  1.0F Color.white 255, 0, 0 1.0F,  0.0F,  0.0F Color.red 255, 175, 175 1.0F,  0.7F,  0.7F Color.pink 255, 200, 0 1.0F,  0.8F,  0.0F Color.orange 255, 0, 255 1.0F,  0.0F,  1.0F Color.magenta RGB Value (integer) RGB Value (float) Color 0, 255, 0 0.0F,  1.0F,  0.0F Color.green 192, 192, 192 0.75F,  0.75F,  0.75F Color.lightGray 64, 64, 64 0.25F,  0.25F,  0.25F Color.darkGray 128, 128, 128 0.5F,  0.5F,  0.5F Color.gray 0, 255, 255 0.0F,  1.0F,  1.0F Color.cyan 0, 0, 255 0.0F,  0.0F,  1.0F Color.blue 0, 0, 0 0.0F,  0.0F,  0.0F Color.black RGB Value (integer) RGB Value (float) Color
Colors  (cont’d) A Color object can be created using one of two constructors: Color(int red, int green, int blue) Color(float red, float green, float blue) For example: Color  c1  =  new  Color(255,  100,  18); Color  c2  =  new  Color(0.2F,  0.6F,  0.3F); By default, the Graphics object has a  black foreground  and a  light gray background . This can be changed using the following methods (of the Graphics object): void  setBackground(Color newColor) void  setForeground(Color  newColor) void  setColor(Color newColor)
Colors  (cont’d) The following example displays some strings in different colors. Although it is possible to set the background and foreground colors in the  paint()  method, a good place to set these colors is in the  init()  method.  import java.awt.*; import java.applet.*; public class MyApplet extends Applet { public void init() { setBackground(Color.blue); setForeground(Color.yellow); } public void paint(Graphics  g) { g.drawString(&quot;A yellow string&quot;, 50, 10); g.setColor(Color.red) ; g.drawString(&quot;A red string&quot;, 50, 50); g.drawString(&quot;Another red string&quot;, 50, 90); g.setColor(Color.magenta) ; g.drawString(&quot;A magenta string&quot;, 50, 130); } }
Drawing Some Shapes An oval can be drawn using the method  drawOval()  as follows: void  drawOval( int x, int y, int width, int height ) A rectangle can be drawn using the method  drawRect()  as follows: void  drawRect( int x, int y, int width, int height ) A line linking two points can be drawn using the method  drawLine()  as follows: void  drawLine( int x1, int y1, int x2, int y2 )   To draw a shape using a specific color, the method setColor() should be used before drawing the shape. There are no methods called drawCircle() or drawSquare(). How can we draw a circle or a square..???
Executing a Java Applet A Java applet must be compiled into bytecode before it can be used in a web page. When a web page containing an  <applet>  tag is opened, the associated bytecode is downloaded from the location specified by the CODE or CODEBASE attribute. This location can be in  the local machine  or in a  machine across the web . To interpret the applet bytecode, the browser must have a  Java plug-in . Also, an applet can be executed using the  applet viewer , which comes with the JDK.
Comparing Applets with Applications Has a  restricted access  to the machine resources (cannot open files or run other programs)  {Security reasons} Has an  unrestricted access  to the machine resources Almost always works with  GUI Can work with  command-line  (like what are always doing), or using a  graphical user-interface  (GUI) {More on this in ICS-201} Has to extend  java.applet.Applet  class Doesn’t have to extend any class Starts by the  init()  method Starts by the  main()  method Has to run  inside  another program, called execution environment (like  a web browser  or  an applet viewer ) Runs  independently An Applet An Application
A Simple Java Applet: Drawing a String Now, create applets of our own Take a while before we can write applets like in the demos Cover many of same techniques Upcoming program Create an applet to display  &quot;Welcome to Java Programming!&quot; Show applet and HTML file, then discuss them line by line
Java applet Program Output 1  // Fig. 3.6: WelcomeApplet.java 2  // A first applet in Java. 3  4  // Java core packages 5  import  java.awt.Graphics;  // import class Graphics 6  7  // Java extension packages 8  import  javax.swing.JApplet;  // import class JApplet 9  10  public class  WelcomeApplet  extends  JApplet {  11  12  // draw text on applet’s background 13  public void  paint( Graphics g ) 14  { 15  // call inherited version of method paint 16  super .paint( g ); 17  18  // draw a String at x-coordinate 25 and y-coordinate 25 19  g.drawString(  &quot;Welcome to Java Programming!&quot; ,  25 ,  25  ); 20  21  }  // end method paint 22  23  }  // end class WelcomeApplet import  allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends  allows us to inherit the capabilities of class  JApplet . Method  paint  is guaranteed to be called in all applets.  Its first line must be defined as above.
3.3 A Simple Java Applet: Drawing a String Comments Name of source code and description of applet Import predefined classes grouped into packages import  statements tell compiler where to locate classes used When you create applets,  import  the  JApplet  class (package  javax.swing ) import  the  Graphics  class (package  java.awt ) to draw graphics  Can draw lines, rectangles ovals, strings of characters import  specifies directory structure 5  import  java.awt.Graphics;  // import class Graphics 8  import  javax.swing.JApplet;  // import class JApplet // Fig. 3.6: WelcomeApplet.java 2  // A first applet in Java.
3.3 A Simple Java Applet: Drawing a String Applets have at least one class definition (like applications) Rarely create classes from scratch Use pieces of existing class definitions Inheritance - create new classes from old ones (ch. 15) Begins  class  definition for class  WelcomeApplet Keyword  class  then class name extends  followed by class name Indicates class to inherit from ( JApplet ) JApplet  : superclass (base class) WelcomeApplet  : subclass (derived class) WelcomeApplet  now has methods and data of  JApplet 10  public class  WelcomeApplet  extends  JApplet {
3.3 A Simple Java Applet: Drawing a String Class  JApplet  defined for us Someone else defined &quot;what it means to be an applet&quot; Applets require over 200 methods! extends JApplet Inherit methods, do not have to define them all Do not need to know every detail of class  JApplet 10  public class  WelcomeApplet  extends  JApplet {
3.3 A Simple Java Applet: Drawing a String Class  WelcomeApplet  is a blueprint appletviewer  or browser creates an object of class  WelcomeApplet Keyword  public  required File can only have one  public  class  public  class name must be file name 10  public class  WelcomeApplet  extends  JApplet {
3.3 A Simple Java Applet: Drawing a String Our class inherits method  paint  from  JApplet By default,  paint  has empty body Override (redefine)  paint  in our class Methods  paint ,  init , and  start Guaranteed to be called automatically Our applet gets &quot;free&quot; version of these by inheriting from  JApplet Free versions have empty body (do nothing) Every applet does not need all three methods  Override the ones you need Applet container “draws itself” by calling method  paint 13  public void  paint( Graphics g )
3.3 A Simple Java Applet: Drawing a String Method  paint Lines 13-21 are the definition of paint Draws graphics on screen void  indicates  paint  returns nothing when finishes task Parenthesis define parameter list - where methods receive data to perform tasks Normally, data passed by programmer, as in  JOptionPane.showMessageDialog paint  gets parameters automatically Graphics  object used by  paint Mimic  paint 's first line 13  public void  paint( Graphics g )
3.3 A Simple Java Applet: Drawing a String Calls version of method paint from superclass  JApplet Should be first statement in every applet’s paint method Body of  paint Method  drawString  (of class  Graphics ) Called using  Graphics  object  g  and dot operator ( . ) Method name, then parenthesis with arguments First argument:  String  to draw Second: x coordinate (in pixels) location Third: y coordinate  (in pixels) location Java coordinate system Measured in pixels (picture elements) Upper left is ( 0 , 0 ) 16  super .paint( g ); 19  g.drawString(  &quot;Welcome to Java Programming!&quot; ,  25 ,  25  );
3.3.1  Compiling and Executing WelcomeApplet Running the applet Compile javac WelcomeApplet.java If no errors, bytecodes stored in  WelcomeApplet.class Create an HTML file  Loads the applet into  appletviewer  or a browser Ends in  .htm  or  .html To execute an applet Create an HTML file indicating which applet the browser (or  appletviewer ) should load and execute
3.3.1  Compiling and Executing WelcomeApplet Simple HTML file ( WelcomeApplet.html ) Usually in same directory as  .class  file Remember,  .class  file created after compilation HTML codes (tags) Usually come in pairs Begin with  <  and end with  > Lines 1 and 4 - begin and end the HTML tags Line 2 - begins  <applet>  tag Specifies code to use for applet Specifies  width  and  height  of display area in pixels Line 3 - ends  <applet>  tag 1  <html> 2  <applet code =  &quot;WelcomeLines.class&quot;   width =  &quot;300&quot;  height =  &quot;40&quot; > 3  </applet> 4  </html>
3.3.1  Compiling and Executing WelcomeApplet appletviewer  only understands  <applet>  tags Ignores everything else Minimal browser Executing the applet appletviewer WelcomeApplet.html Perform in directory containing  .class  file 1  <html> 2  <applet code =  &quot;WelcomeLines.class&quot;   width =  &quot;300&quot;  height =  &quot;40&quot; > 3  </applet> 4  </html>
3.4 Two More Simple Applets: Drawing Strings and Lines More applets First example Display two lines of text Use  drawString  to simulate a new line with two  drawString  statements Second example Method  g.drawLine(x1, y1, x2, y2 ) Draws a line from ( x1 ,  y1 ) to ( x2 ,  y2 ) Remember that ( 0 ,  0 ) is upper left Use  drawLine  to draw a line beneath and above a string
1  // Fig. 3.8: WelcomeApplet2.java 2  // Displaying multiple strings in an applet. 3  4  // Java core packages 5  import  java.awt.Graphics;  // import class Graphics 6  7  // Java extension packages 8  import  javax.swing.JApplet;  // import class JApplet 9  10  public class  WelcomeApplet2  extends  JApplet {  11  12  // draw text on applet’s background 13  public void  paint( Graphics g ) 14  { 15  // call inherited version of method paint 16  super .paint( g ); 17  18  // draw two Strings at different locations 19  g.drawString(  &quot;Welcome to&quot; ,  25 ,  25  ); 20  g.drawString(  &quot;Java Programming!&quot; ,  25 ,  40  ); 21  22  }  // end method paint 23  24  }  // end class WelcomeApplet2 1.  import 2. Class  WelcomeApplet2  ( extends JApplet ) 3.  paint 3.1  drawString 3.2  drawString on same x coordinate, but 15 pixels down The two  drawString  statements simulate a newline.  In fact, the concept of lines of text does not exist when drawing strings.
HTML file Program Output 1  <html> 2  <applet code =  &quot;WelcomeApplet2.class&quot;  width =  &quot;300&quot;  height =  &quot;60&quot; > 3  </applet> 4  </html>
WelcomeLines.java  2. Class  WelcomeLines  ( extends JApplet ) 3.  paint 3.1  drawLine 3.2  drawLine 3.3  drawString   Program Output 1  // Fig. 3.10: WelcomeLines.java 2  // Displaying text and lines 3  4  // Java core packages 5  import  java.awt.Graphics;  // import class Graphics 6  7  // Java extension packages 8  import  javax.swing.JApplet;  // import class JApplet 9  10  public class  WelcomeLines  extends  JApplet {  11  12  // draw lines and a string on applet’s background 13  public void  paint( Graphics g ) 14  { 15  // call inherited version of method paint 16  super .paint( g ); 17  18  // draw horizontal line from (15, 10) to (210, 10) 19  g.drawLine(  15 ,  10 ,  210 ,  10  );  20  21  // draw horizontal line from (15, 30) to (210, 30) 22  g.drawLine(  15 ,  30 ,  210 ,  30  );  23  24  // draw String between lines at location (25, 25) 25  g.drawString(  &quot;Welcome to Java Programming!&quot; ,  25 ,  25  ); 26  27  }  // end method paint 28  29  }  // end class WelcomeLines Draw horizontal lines with  drawLine  (endpoints have same y coordinate).
HTML file 1  <html> 2  <applet code =  &quot;WelcomeLines.class&quot;   width =  &quot;300&quot;  height =  &quot;40&quot; > 3  </applet> 4  </html>
3.4 Two More Simple Applets: Drawing Strings and Lines Method  drawLine  of class  Graphics Takes as arguments  Graphics  object and line’s end points X and y coordinate of first endpoint X and y coordinate of second endpoint
3.5  Another Java Applet: Adding Floating-Point Numbers Next applet Mimics application for adding two integers (Fig 2.9) This time, use floating point numbers (numbers with a decimal point) Using primitive data types Double  – double precision floating-point numbers Float  – single precision floating-point numbers Show program, then discuss
AdditionApplet.java 1.  import 2. Class  AdditionApplet  ( extends JApplet ) 3. Instance variable  4.  init 4.1 Declare variables 4.2  showInputDialog 4.3  parseDouble 1  // Fig. 3.12: AdditionApplet.java 2  // Adding two floating-point numbers. 3  4  // Java core packages 5  import  java.awt.Graphics;  // import class Graphics 6  7  // Java extension packages 8  import  javax.swing.*;  // import package javax.swing 9  10  public class  AdditionApplet  extends  JApplet { 11  double  sum;  // sum of values entered by user 12  13  // initialize applet by obtaining values from user 14  public void init () 15  { 16  String firstNumber;  // first string entered by user 17  String secondNumber;  // second string entered by user 18  double  number1;  // first number to add 19  double  number2;  // second number to add 20  21  // obtain first number from user 22  firstNumber = JOptionPane.showInputDialog( 23  &quot;Enter first floating-point value&quot;  ); 24  25  // obtain second number from user 26  secondNumber = JOptionPane.showInputDialog( 27  &quot;Enter second floating-point value&quot;  ); 28  29  // convert numbers from type String to type double 30  number1 = Double.parseDouble( firstNumber );  31  number2 = Double.parseDouble( secondNumber ); 32  2 // Adding two floating-point numbers 3 import java.awt.Graphics;  // import class Graphics 5 6 public class AdditionApplet extends JApplet { 7   double sum;  // sum of the values entered by the user 8 9   public void init() 10   { 11   String firstNumber,  // first string entered by user 12   secondNumber;  // second string entered by user 13   double number1,  // first number to add 14   number2;  // second number to add 15 16   // read in first number from user 17   firstNumber = 18   JOptionPane.showInputDialog( 19   &quot;Enter first floating-point value&quot; ); 20 21   // read in second number from user 22   secondNumber = 23   JOptionPane.showInputDialog( 24   &quot;Enter second floating-point value&quot; ); 25 26 27   // convert numbers from type String to type double *  allows any class in the the package to be used. Instance variable  sum  may be used anywhere in the class, even in other methods. Data type  double  can store floating point numbers.
5. Draw applet contents 5.1 Draw a rectangle 5.2 Draw the results HTML file 33  // add numbers 34  sum = number1 + number2; 35  } 36  37  // draw results in a rectangle on applet’s background 38  public void  paint( Graphics g ) 39  { 40  // call inherited version of method paint 41  super .paint( g ); 42  43  // draw rectangle starting from (15, 10) that is 270  44  // pixels wide and 20 pixels tall 45  g.drawRect(  15 ,  10 ,  270 ,  20  ); 46  47  // draw results as a String at (25, 25) 48  g.drawString(  &quot;The sum is &quot;  + sum,  25 ,  25  ); 49  50  }  // end method paint 51  52  }  // end class AdditionApplet 1  <html> 2  <applet code =  &quot;WelcomeLines.class&quot;   width =  &quot;300&quot;  height =  &quot;40&quot; > 3  </applet> 4  </html> 31   // add the numbers 32   sum = number1 + number2; 33   } 34 35   public void paint( Graphics g ) 36   { 37   // draw the results with g.drawString 38   g.drawRect( 15, 10, 270, 20 ); 39   g.drawString( &quot;The sum is &quot; + sum, 25, 25 ); 40   } 41 } 1 <html> 2 <applet code=&quot;AdditionApplet.class&quot; width=300 height=50> 3 </applet> 4 </html> drawRect  takes the upper left coordinate, width, and height of the rectangle to draw.
Program Output
3.5  Another Java Applet: Adding Floating-Point Numbers Lines 1-2: Comments Line 5:  import s class  Graphics import  not needed if use full package and class name public void paint ( java.awt.Graphics g ) Line 8: specify entire  javax.swing  package *  indicates all classes in  javax.swing  are available Includes  JApplet  and  JOptionPane Use  JOptionPane  instead of  javax.swing.JOptionPane *  does not not load all classes  Compiler only loads classes it uses 5  import  java.awt.Graphics; 8  import  javax.swing.*;
3.5  Another Java Applet: Adding Floating-Point Numbers Begin class definition Inherit from  JApplet ,  import ed from package  javax.swing Instance variable declaration Each object of class gets own copy of the instance variable Declared in body of class, but not inside methods Variables declared in methods are local variables Can only be used in body of method Instance variables can be used anywhere in class Have default value ( 0.0  in this case) 10  public class  AdditionApplet  extends  JApplet { 11  double  sum;  // sum of values entered by user
3.5  Another Java Applet: Adding Floating-Point Numbers Primitive data type  double Used to store floating point (decimal) numbers Method  init Normally initializes instance variables and applet class Guaranteed to be first method called in applet First line must always appear as above Returns nothing ( void ), takes no arguments Begins body of method  init 11  double  sum;  // sum of values entered by user 14  public void init ()   15  {
3.5  Another Java Applet: Adding Floating-Point Numbers Declare variables Two types of variables Reference variables (called references) Refer to objects (contain location in memory) Objects defined in a class definition Can contain multiple data and methods paint  receives a reference called  g  to a  Graphics  object Reference used to call methods on the  Graphics  object Primitive data types  (called variables) Contain one piece of data 16  String firstNumber;  // first string entered by user 17  String secondNumber;  // second string entered by user 18  double  number1;  // first number to add 19  double  number2;  // second number to add
3.5  Another Java Applet: Adding Floating-Point Numbers Distinguishing references and variables If data type is a class name, then reference String  is a class firstNumber ,  secondNumber If data type a primitive type, then variable double  is a primitive data type number1 ,  number2 16  String firstNumber;  // first string entered by user 17  String secondNumber;  // second string entered by user 18  double  number1;  // first number to add 19  double  number2;  // second number to add
3.5  Another Java Applet: Adding Floating-Point Numbers Method  JOptionPane.showInputDialog Prompts user for input with string Enter value in text field, click  OK If not of correct type, error occurs In Chapter 14 learn how to deal with this Returns string user inputs Assignment statement to string Lines 26-27: As above, assigns input to  secondNumber 22  firstNumber = JOptionPane.showInputDialog( 23  &quot;Enter first floating-point value&quot;  );
3.5  Another Java Applet: Adding Floating-Point Numbers static  method  Double.parseDouble Converts  String  argument to a  double Returns the  double  value Remember static method syntax ClassName.methodName( arguments ) Assignment statement sum  an instance variable, can use anywhere in class Not defined in  init  but still used 34  sum = number1 + number2; 30  number1 = Double.parseDouble( firstNumber );  31  number2 = Double.parseDouble( secondNumber );
3.5  Another Java Applet: Adding Floating-Point Numbers Ends method  init appletviewer  (or browser) calls inherited method  start start  usually used with multithreading Advanced concept, in Chapter 15 We do not define it, so empty definition in  JApplet  used Next, method  paint  called Method  drawRect( x1, y1, width, height ) Draw rectangle, upper left corner ( x1, y1 ), specified  width  and  height Line 45 draws rectangle starting at (15, 10) with a width of 270 pixels and a height of 20 pixels 33   }   45  g.drawRect(  15 ,  10 ,  270 ,  20  );
3.5  Another Java Applet: Adding Floating-Point Numbers Sends  drawString  message (calls method) to  Graphics  object using reference  g &quot;The sum is&quot; + sum  - string concatenation sum  converted to a string sum  can be used, even though not defined in  paint Instance variable, can be used anywhere in class Non-local variable   48  g.drawString(  &quot;The sum is &quot;  + sum,  25 ,  25  );
3.6  Viewing Applets in a Web Browser Applets can execute on Java-enabled browsers Many different browser version supporting different Java version specifications Some support for Java 1.0, many for Java 1.1 inconsistently Netscape Navigator 6 supports Java 2 (section 3.6.1) Use Java Plug-in to execute Java 2 applets on other browsers (section 3.6.2)
Fonts By default, strings are drawn using the default font, plain style and default font size. To change the font, style or size, we need to create an object of class  java.awt.Font  and pass it to the  setFont()  method of the graphics object used in the paint() method. To create such a Font object, we need to specify the following parameters: The font name. The Style (Font.PLAIN, Font.BOLD, Font.ITALIC, or  Font.BOLD + Font.ITALIC). The font size. The font name can be the name of any font available on the particular computer (such as: TimesRoman, Courier, Helvetica  etc.,) or any of the logical names shown in the table below: A screen font suitable for user input in text fields DialogInput A screen font suitable for labels in dialogs Dialog A font in which all characters have the same width. e.g. Courier Monospaced A font without small segments, e.g. Helvetica SansSerif A font with small segments at the end, e.g. Times New Roman Serif
Fonts  (cont’d)   Example: The following applet displays the word  Applet  in large SansSerif font. import java.applet.*; import java.awt.*; public class BigFontApplet extends Applet{ public void paint(Graphics g){  final int SIZE = 48;   Color myColor = new Color(0.25F, 0.5F, 0.75F);   Font myFont = new Font(&quot;SansSerif&quot;, Font.BOLD, SIZE);   g.setColor(myColor);   g.setFont(myFont);   g.drawString(&quot;Applet&quot;,5,60); } }
Fonts  (cont’d)   If an applet will use  several fonts , it is good to create the font objects in the  init()  method: import java.applet.*; import java.awt.*; public class FontExamples extends Applet{   private Font f, fb, fi, fbi;   public void init() {   setBackground(Color.yellow);   f = new Font(&quot;TimesRoman&quot;, Font.PLAIN, 18);   fb = new Font(&quot;Courier&quot;, Font.BOLD, 20);   fi = new Font(&quot;TimesRoman&quot;, Font.ITALIC, 18);   fbi = new Font(&quot;Helvetica&quot;, Font.BOLD + Font.ITALIC, 25);   }   public void paint(Graphics g){   g.setColor(Color.blue);   g.setFont(f);   g.drawString(&quot;This is TimesRoman plain font&quot;, 10, 25);   //...   } }
Drawing in an Applet import java.applet.Applet; import java.awt.*; // assume that the drawing area is 150 by 150 public class SquareAndRectangle extends Applet { final int areaSide = 150 ; final int width = 100, height = 50; public void paint ( Graphics gr ) {  setBackground( Color.green ); gr.setColor( Color.red ); // outline the drawing area gr.drawRect( 0, 0, areaSide-1, areaSide-1 );  // draw interiour rectange. gr.drawRect( areaSide/2 - width/2 ,  areaSide/2 - height/2, width, height );  } }
Java’s coordinate system Java uses an (x, y) coordinate system (0, 0) is the top left corner (50, 0) is 50 pixels to the right of (0, 0) (0, 20) is 20 pixels down from (0, 0) (w - 1, h - 1) is just inside the bottom right corner, where w is the width of the window and h is its height (0, 0) (0, 20) (50, 0) (50, 20) (w-1, h-1) (50, 0) (0, 0) (0, 20) (50, 20)
Drawing rectangles There are two ways to draw rectangles: g.drawRect(   left   ,   top   ,   width   ,   height   ); g.fillRect( left   ,   top   ,   width   ,   height   );
Drawing strings A  String  is a sequence of characters enclosed in double quote marks &quot;Hello, World!&quot; A double quote mark in a  String  must be preceded by a backslash (  \  ) &quot;He said, \&quot;Please don't go!\&quot; &quot; To draw a string, you need to specify not only  what  you want to say, but  where  to say it g.drawString(  string ,  left ,  top  ); For example, g.drawString(&quot;Example JApplet&quot;, 20, 80);
The complete applet import javax.swing.JApplet; import java.awt.*; // CIT 591 example public class Drawing extends JApplet { public void paint(Graphics g) { g.setColor(Color.BLUE);   g.fillRect(20, 20, 50, 30);   g.setColor(Color.RED);   g.fillRect(50, 30, 50, 30);   g.setColor(Color.BLACK);   g.drawString(&quot;Example JApplet&quot;, 20, 80);   } }
More  java.awt.Graphics  methods g.drawLine( x1 ,   y1 ,   x2 ,   y2 ); g.drawOval( left ,   top ,   width ,   height ); g.fillOval( left ,   top ,   width ,   height ); g.drawRoundRect( left ,   top ,   width ,   height,   arcWidth ,  arcHeight ); arcWidth ,  arcHeight  define the “roundedness” of corners g.fillRoundRect( left ,   top ,   width ,   height, arcWidth ,  arcHeight ); g.drawArc(  left ,   top ,   width ,   height ,  startAngle ,   arcAngle ); Angles are in degrees 0 degrees is the 3 o’clock position Positive angles are to the right g.FillArc(  left ,   top ,   width ,   height ,  startAngle ,   arcAngle );
Still more  Graphics  methods g.drawPolygon( xPoints ,  yPoints ,  n ); g.fillPolygon( xPoints ,  yPoints ,  n ); xPoints   and   yPoints   are  int  arrays of size   n One way to write an  int  array is:   new int[] {  value1 ,  value2 , ...,  valueN } Example:  g.drawPolygon(new int[] { 250, 290, 210 },                     new int[] { 210, 290, 290 }, 3); draws a triangle using the 3 points (250, 210), (290, 290), and (210, 290). g.drawPolyline( xPoints ,  yPoints ,  n ); A “polyline” is like a polygon, except the first and last points are not automatically connected Hence, there is no “fillPolyline” method
The HTML page You can only run an applet from an HTML page The HTML looks something like this: <html>   <body>   <h1>Drawing Applet</h1>   <applet code=&quot;Drawing.class&quot;    width=&quot;100&quot;  height=&quot;150&quot;>    </applet>   </body> </html> Eclipse will create this HTML for you You don’t even need to think about the HTML just yet
Other useful JApplet methods System.out.println(String  s ) Works from  appletviewer , not from browsers Automatically opens an output window. showStatus(String  s )  displays the String in the applet’s status line. Each call overwrites the previous call. You have to allow time to read the line!

More Related Content

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
Prawesh Shrestha
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
Mallikarjuna G D
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
AbhishekMondal42
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Access modifier and inheritance
Access modifier and inheritanceAccess modifier and inheritance
Access modifier and inheritance
Dikshyanta Dhungana
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
JVM
JVMJVM
JVM
baabtra.com - No. 1 supplier of quality freshers
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
myrajendra
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 

Viewers also liked (20)

Java applets
Java appletsJava applets
Java applets
Srinath Dhayalamoorthy
 
Java applets
Java appletsJava applets
Java applets
lopjuan
 
Java applets
Java appletsJava applets
Java applets
Khan Mac-arther
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
amitksaha
 
Applet java
Applet javaApplet java
Applet java
Jorge Luis Tinoco
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
Ravindra Rathore
 
Java Applets
Java AppletsJava Applets
Java Applets
Danial Mirza
 
Java applet
Java appletJava applet
Java applet
Arati Gadgil
 
6.applet programming in java
6.applet programming in java6.applet programming in java
6.applet programming in java
Deepak Sharma
 
applet using java
applet using javaapplet using java
applet using java
Kartik Kalpande Patil
 
Java Applet
Java AppletJava Applet
Java Applet
Shree M.L.Kakadiya MCA mahila college, Amreli
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in java
Atul Sehdev
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
yugandhar vadlamudi
 
Java Applet
Java AppletJava Applet
Java Applet
Athharul Haq
 
L18 applets
L18 appletsL18 applets
L18 applets
teach4uin
 
Java Programming- Introduction to Java Applet Programs
Java Programming- Introduction to Java Applet ProgramsJava Programming- Introduction to Java Applet Programs
Java Programming- Introduction to Java Applet Programs
Trinity Dwarka
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Applet Vs Servlet
Applet Vs ServletApplet Vs Servlet
Applet Vs Servlet
Bharat Sahu
 
Java EE - Servlets API
Java EE - Servlets APIJava EE - Servlets API
Java EE - Servlets API
Brice Argenson
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Ad

Similar to Java: Java Applets (20)

Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
Abhishek Khune
 
Applet.pptx
Applet.pptxApplet.pptx
Applet.pptx
LakachewYezihalem
 
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt
Applets(1)cusdhsiohisdhfshihfsihfohf.pptApplets(1)cusdhsiohisdhfshihfsihfohf.ppt
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt
Vijay Bhaskar Thatty
 
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
Appletsbjhbjiibibibikbibibjibjbibbjb.pptAppletsbjhbjiibibibikbibibjibjbibbjb.ppt
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
Vijay Bhaskar Thatty
 
Applets
AppletsApplets
Applets
Inayat Sharma
 
Applets
AppletsApplets
Applets
Abhishek Khune
 
Applet in java new
Applet in java newApplet in java new
Applet in java new
Kavitha713564
 
Applets
AppletsApplets
Applets
Nuha Noor
 
applet.pptx
applet.pptxapplet.pptx
applet.pptx
SachinBhosale73
 
Introduction To Applets methods and simple examples
Introduction To Applets methods  and simple examplesIntroduction To Applets methods  and simple examples
Introduction To Applets methods and simple examples
MsPariyalNituLaxman
 
MSBTE Computer Engineering Java applet.pptx
MSBTE Computer Engineering Java applet.pptxMSBTE Computer Engineering Java applet.pptx
MSBTE Computer Engineering Java applet.pptx
kunalgaikwad1705
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
arnold 7490
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
Kuntal Bhowmick
 
Advanced Programming, Java Programming, Applets.ppt
Advanced Programming, Java Programming, Applets.pptAdvanced Programming, Java Programming, Applets.ppt
Advanced Programming, Java Programming, Applets.ppt
miki304759
 
Applet intro
Applet introApplet intro
Applet intro
Nitin Birari
 
Jsp applet
Jsp appletJsp applet
Jsp applet
Sanoj Kumar
 
Applets in Java. Learn java program with applets
Applets in Java. Learn java program with appletsApplets in Java. Learn java program with applets
Applets in Java. Learn java program with applets
halaplay385
 
Java applet
Java appletJava applet
Java applet
GaneshKumarKanthiah
 
Java applet - java
Java applet - javaJava applet - java
Java applet - java
Rubaya Mim
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
Abhishek Khune
 
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt
Applets(1)cusdhsiohisdhfshihfsihfohf.pptApplets(1)cusdhsiohisdhfshihfsihfohf.ppt
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt
Vijay Bhaskar Thatty
 
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
Appletsbjhbjiibibibikbibibjibjbibbjb.pptAppletsbjhbjiibibibikbibibjibjbibbjb.ppt
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
Vijay Bhaskar Thatty
 
Introduction To Applets methods and simple examples
Introduction To Applets methods  and simple examplesIntroduction To Applets methods  and simple examples
Introduction To Applets methods and simple examples
MsPariyalNituLaxman
 
MSBTE Computer Engineering Java applet.pptx
MSBTE Computer Engineering Java applet.pptxMSBTE Computer Engineering Java applet.pptx
MSBTE Computer Engineering Java applet.pptx
kunalgaikwad1705
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
Kuntal Bhowmick
 
Advanced Programming, Java Programming, Applets.ppt
Advanced Programming, Java Programming, Applets.pptAdvanced Programming, Java Programming, Applets.ppt
Advanced Programming, Java Programming, Applets.ppt
miki304759
 
Applets in Java. Learn java program with applets
Applets in Java. Learn java program with appletsApplets in Java. Learn java program with applets
Applets in Java. Learn java program with applets
halaplay385
 
Java applet - java
Java applet - javaJava applet - java
Java applet - java
Rubaya Mim
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
Ad

More from Tareq Hasan (20)

Grow Your Career with WordPress
Grow Your Career with WordPressGrow Your Career with WordPress
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org RepositoryHow to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Composer - The missing package manager for PHPComposer - The missing package manager for PHP
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
chapter22.ppt
chapter22.pptchapter22.ppt
chapter22.ppt
Tareq Hasan
 
chapter - 6.ppt
chapter - 6.pptchapter - 6.ppt
chapter - 6.ppt
Tareq Hasan
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
Tareq Hasan
 
chapter-8.ppt
chapter-8.pptchapter-8.ppt
chapter-8.ppt
Tareq Hasan
 
chapter23.ppt
chapter23.pptchapter23.ppt
chapter23.ppt
Tareq Hasan
 
chapter24.ppt
chapter24.pptchapter24.ppt
chapter24.ppt
Tareq Hasan
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
Tareq Hasan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Grow Your Career with WordPress
Grow Your Career with WordPressGrow Your Career with WordPress
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org RepositoryHow to Submit a plugin to WordPress.org Repository
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Composer - The missing package manager for PHPComposer - The missing package manager for PHP
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011WordPress Theme & Plugin development best practices - phpXperts seminar 2011
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 

Recently uploaded (20)

Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 

Java: Java Applets

  • 2. Introducing Applets Applets Java programs called from within another application Frequently run from a Web page Display as rectangular area Can respond to user-initiated events Behaviors come from Java class named JApplet Steps to write an applet Set up layout for applet Create components and add them to applet
  • 3. Applets An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page to tell the browser about the applet You don’t need to supply a main method; the browser does that When you write an applet, you are writing only part of a program You supply certain methods that the browser calls For security reasons, applets run in a sandbox : they have no access to the client’s file system
  • 4. What an applet is You write an applet by extending the class JApplet JApplet is just a class like any other; you can even use it in applications if you want When you write an applet, you are only writing part of a program; the browser supplies the main method Once you understand how applets work, you can write a program that function either as an applet or as an application—just write a main method that calls the right methods at the right time Such programs have the ugly name “ appletcations ”
  • 5. The genealogy of JApplet java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet | +----javax.swing.JApplet
  • 6. The simplest possible applet import javax.swing.JApplet; public class TrivialApplet extends JApplet { } <applet code=&quot;TrivialApplet.class&quot; width=&quot;150&quot; height=&quot;100&quot;> </applet> TrivialApplet.java TrivialApplet.html
  • 7. The simplest reasonable applet import java.awt.*; import javax.swing.JApplet; public class HelloWorld extends JApplet { public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 30, 30); } }
  • 8. What are the disadvantages of applets? Applets can’t run any local executable programs Applets can’t with any host other than the originating server Applets can’t read/write to local computer’s file system
  • 9. What are the disadvantages of applets? (Cont’d) Applets can’t find any information about the local computer All java-created pop-up windows carry a warning message Stability depends on stability of the client’s web server Performance directly depend on client’s machine
  • 10. What are the advantages of applets? Automatically integrated with HTML; hence, resolved virtually all installation issues. Can be accessed from various platforms and various java-enabled web browsers. Can provide dynamic, graphics capabilities and visualizations Implemented in Java, an easy-to-learn OO programming language
  • 11. What are the advantages of applets? (Cont’d) Alternative to HTML GUI design Safe! Because of the security built into the core Java language and the applet structure, you don’t have to worry about bad code causing damage to someone’s system Can be launched as a standalone web application independent of the host web server
  • 12. Java Applets Can not Applets are programs designed to run as part of a Web Page (Applet = little application). Applets are similar to normal Java Applications but have extra security features to prevent a downloaded Applet damaging your computer or transmitting information from it. For instance an Applet cannot: Access local files Delete local files Run another program Find out your name Connect to another host
  • 13. Running a Java Applet You write Java code using an editor javac MyApp.java appletviewer MyApp.html Text Editor You save the file with a .java extension You run the Java compiler ' javac ' You can view the applet with the command ' appletviewer ' This creates a file of bytecode with a .class extension Web Browser You write a web page in html using an editor You can view the web page from a web browser You save the file with a .html extension Java code: MyApp.java Bytecode: MyApp.class Window Web page: MyApp.html Text Editor
  • 14. Creating an Applet  Open &quot; Notepad &quot; (Start  Programs  Other  Notepad)  Type this in:  Save As &quot;Greetings.java&quot; (Put the &quot; &quot; round the name otherwise it adds .txt to the end!)  Open a DOS Window (Start  MS-DOS Prompt)  Type javac Greetings.java G:\> javac Greetings.java G:\> If it gives an error check you typed it in exactly right. import java.awt.*; import java.applet.Applet; public class Greetings extends Applet { public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 50, 50); } }  If you type dir Greetings.* you should see Greetings.java and Greetings.class
  • 15. Creating the Web Page In order to run an applet you have to embed it in a web page using a special <applet> tag e.g: <applet code=&quot;name.class&quot; width=www height=hhh></applet> <html> <head> <title>Greetings Applet</title> </head> <body> <applet code=&quot;Greetings.class&quot; width=300 height=200 ></applet> </body> </html> Using Notepad type in the following and save it as &quot;Greetings.html&quot; : Size of the applet in pixels
  • 16. Running the Program G:\> appletviewer Greetings.html In the DOS window type appletviewer Greetings.html You should see something like this:
  • 17. Running in a Web Browser In Netscape go to the File menu then Open Page ... Press Choose File... Find your file Greetings with the Netscape symbol alongside it (Greetings.html) - click on it and press Open (or double click on it) Back in the Open Page dialog press Open You should see something like: Title Your greeting Message
  • 18. What does it mean? import java.awt.*; import java.applet.Applet; public class Greetings extends Applet { public void paint(Graphics g) { g.drawString(&quot;Hello World!&quot;, 50, 50); } } These 2 lines tell the computer to include ( import ) two standard libraries awt (Abstract Window Toolkit) and applet . This line tells the computer to display some text ( a string) on the screen. This line announces that the program ( class ) can be run by anyone ( public ), is called Greetings and is an Applet . This line declares what follows in the { } as a method called paint. This is where it is displayed in pixels across and down from the top left hand corner This is what is displayed
  • 19. General Form of an Applet New applets are created by extending the Applet class contained in the java . applet package. Also, the package java.awt is needed for the graphical interface of the applet. In general, an applet program would look like the following: import java.applet.*; import java.awt.*; public class AppletName extends Applet { . . . }
  • 20. General Form of an Applet (cont’d) An applet overrides a set of methods in the class Applet to implement its functionality. These methods are used as an interface with the browser or the applet viewer. An applet does not need to override those methods it does not use. The following lists the most important methods that are usually used: import java.applet.*; import java.awt.*; public class AppletName extends Applet { public void init (){ . . . }   public void start (){ . . . }   public void stop (){ . . . }   public void destroy (){ . . .}   public void paint (Graphics g ){ . . .} }
  • 21. Applet Initialization and Termination When an applet begins, the browser calls the following methods, in this sequence: init() , start() . Every time the applet is redrawn, the method paint() is called. When an applet is terminated, the following sequence of methods is invoked: stop() , destroy(). Called just before the applet is terminated. Your applet should override this method if it needs to perform any cleanup prior to its destruction. destroy() Called to suspend execution of the applet. Once stopped, an applet is restarted when the execution environment calls start() . stop() Called by the execution environment when an applet should start or resume execution. It is automatically called after init() when an applet first begins. start() Applets do not usually have main method; instead they have the init() method that, like main() , is invoked by the execution environment. It is the first method called for any applet . It is called only once during the run-time of an applet. init() Comment Method
  • 22. Applet methods public void init () public void start () public void stop () public void destroy () public void paint (Graphics) Also: public void repaint() public void update (Graphics) public void showStatus(String) public String getParameter(String)
  • 23. public void init ( ) init() is the first method to execute init() is an ideal place to initialize variables init() is the best place to define the GUI Components (buttons, text fields, checkboxes, etc.), lay them out, and add listeners to them Almost every applet you ever write will have an init( ) method
  • 24. start( ) , stop( ) and destroy( ) start() and stop( ) are used when the Applet is doing time-consuming calculations that you don’t want to continue when the page is not in front public void start() is called: Right after init( ) Each time the page is loaded and restarted public void stop( ) is called: When the browser leaves the page Just before destroy( ) public void destroy( ) is called after stop( ) Use destroy() to explicitly release system resources (like threads) System resources are usually released automatically
  • 25. Methods are called in this order init and destroy are only called once each start and stop are called whenever the browser enters and leaves the page do some work is code called by your listeners paint is called when the applet needs to be repainted init() start() stop() destroy() do some work
  • 26. public void paint(Graphics g) Needed if you do any drawing or painting other than just using standard GUI Component s Any painting you want to do should be done here, or in a method you call from here Painting that you do in other methods may or may not happen Never call paint( Graphics ) , call repaint( )
  • 27. repaint( ) Call repaint( ) when you have changed something and want your changes to show up on the screen You do not need to call repaint() when something in Java’s own components (Buttons, TextFields, etc.) You do need to call repaint() after drawing commands ( drawRect(...) , fillRect(...) , drawString(...) , etc.) repaint( ) is a request --it might not happen When you call repaint( ) , Java schedules a call to update(Graphics g )
  • 28. update( ) When you call repaint( ) , Java schedules a call to update(Graphics g) Here's what update does: public void update(Graphics g) { // Fills applet with background color, then paint(g); }
  • 29. The paint() method The paint() method is called by the execution environment (i.e. the browser) each time the applet has to be redrawn. The inherited paint() method is empty. In order to draw anything on the applet, this method must be overridden. paint() method takes an object of class Graphics as an input argument, which is passed by the execution environment. public void paint(Graphics g){ . . . } This Graphics object represents a drawing area. It has methods to draw strings and many shapes. Also, it can manipulate fonts and colors.
  • 30. The Graphics Object A Graphics object has a coordinate system that is illustrated below: Anything that is drawn on the Graphics object, appears on the applet. Some of the drawing methods of the Graphics object are: drawString() drawLine() drawRect() drawOval() (0,0) x y
  • 31. Displaying Strings Using the Graphics Object To display a string on the Graphics object, the method drawString() can be used. It has the following arguments: void drawString( String str, int x, int y) str is the string to be displayed, x and y are the coordinates of the top left point of the string. For example, the following applet displays the string “Hello World!!” starting at the point (50,25). Its file name must be HelloApplet.java. import java.applet.*; import java.awt.*; public class HelloApplet extends Applet { public void paint(Graphics g) { // overriding paint() method g.drawString(&quot;Hello world!&quot;, 50, 25); } }
  • 32. Placing an Applet in a Web Page Recall that web pages are written in HTML. HTML language describes the appearance of a page using tags . For example, <html> is a tag. Another tag is <body> . Some tags have a closing tag . For example, <html> is closed by </html> . HTML is based on text, just like Java. You can use any editor (like Notepad or JCreator) to write HTML files. HTML files should have the extension HTML, like (first.html). All HTML pages should look like: <html> <body> The body of the html page… write whatever you like here. </body> </html>
  • 33. Placing an Applet in a Web Page (cont’d) To place an applet in a web page, the <applet> tag is used in the body of an HTML page as follows: < applet code =“HelloApplet.class” width =600 height =100> </ applet > The parts in green are called attributes . The applet tag has three mandatory (non-optional) attributes: code: the name of the class file of the applet. width: the width of the applet, in pixels. height: the height of the applet, in pixels. If the class file is not at the same folder as the HTML page, the codebase attribute is used to indicate the location of the class file relative to the directory that has the HTML page. < applet code =“HelloApplet.class” codebase =“app\” width =600 height =100> </ applet >
  • 34. Colors The class Color of java . awt package is used to define Color objects. All colors can be specified as a mix of three primary colors : red, green, and blue. A particular color can be specified by three integers, each between 0 and 255, or by three float values, each between 0.0 and 1.0. The class Color has some pre-defined colors that are commonly used. 255, 255, 0 1.0F, 1.0F, 0.0F Color.yellow 255, 255, 255 1.0F, 1.0F, 1.0F Color.white 255, 0, 0 1.0F, 0.0F, 0.0F Color.red 255, 175, 175 1.0F, 0.7F, 0.7F Color.pink 255, 200, 0 1.0F, 0.8F, 0.0F Color.orange 255, 0, 255 1.0F, 0.0F, 1.0F Color.magenta RGB Value (integer) RGB Value (float) Color 0, 255, 0 0.0F, 1.0F, 0.0F Color.green 192, 192, 192 0.75F, 0.75F, 0.75F Color.lightGray 64, 64, 64 0.25F, 0.25F, 0.25F Color.darkGray 128, 128, 128 0.5F, 0.5F, 0.5F Color.gray 0, 255, 255 0.0F, 1.0F, 1.0F Color.cyan 0, 0, 255 0.0F, 0.0F, 1.0F Color.blue 0, 0, 0 0.0F, 0.0F, 0.0F Color.black RGB Value (integer) RGB Value (float) Color
  • 35. Colors (cont’d) A Color object can be created using one of two constructors: Color(int red, int green, int blue) Color(float red, float green, float blue) For example: Color c1 = new Color(255, 100, 18); Color c2 = new Color(0.2F, 0.6F, 0.3F); By default, the Graphics object has a black foreground and a light gray background . This can be changed using the following methods (of the Graphics object): void setBackground(Color newColor) void setForeground(Color newColor) void setColor(Color newColor)
  • 36. Colors (cont’d) The following example displays some strings in different colors. Although it is possible to set the background and foreground colors in the paint() method, a good place to set these colors is in the init() method. import java.awt.*; import java.applet.*; public class MyApplet extends Applet { public void init() { setBackground(Color.blue); setForeground(Color.yellow); } public void paint(Graphics g) { g.drawString(&quot;A yellow string&quot;, 50, 10); g.setColor(Color.red) ; g.drawString(&quot;A red string&quot;, 50, 50); g.drawString(&quot;Another red string&quot;, 50, 90); g.setColor(Color.magenta) ; g.drawString(&quot;A magenta string&quot;, 50, 130); } }
  • 37. Drawing Some Shapes An oval can be drawn using the method drawOval() as follows: void drawOval( int x, int y, int width, int height ) A rectangle can be drawn using the method drawRect() as follows: void drawRect( int x, int y, int width, int height ) A line linking two points can be drawn using the method drawLine() as follows: void drawLine( int x1, int y1, int x2, int y2 ) To draw a shape using a specific color, the method setColor() should be used before drawing the shape. There are no methods called drawCircle() or drawSquare(). How can we draw a circle or a square..???
  • 38. Executing a Java Applet A Java applet must be compiled into bytecode before it can be used in a web page. When a web page containing an <applet> tag is opened, the associated bytecode is downloaded from the location specified by the CODE or CODEBASE attribute. This location can be in the local machine or in a machine across the web . To interpret the applet bytecode, the browser must have a Java plug-in . Also, an applet can be executed using the applet viewer , which comes with the JDK.
  • 39. Comparing Applets with Applications Has a restricted access to the machine resources (cannot open files or run other programs) {Security reasons} Has an unrestricted access to the machine resources Almost always works with GUI Can work with command-line (like what are always doing), or using a graphical user-interface (GUI) {More on this in ICS-201} Has to extend java.applet.Applet class Doesn’t have to extend any class Starts by the init() method Starts by the main() method Has to run inside another program, called execution environment (like a web browser or an applet viewer ) Runs independently An Applet An Application
  • 40. A Simple Java Applet: Drawing a String Now, create applets of our own Take a while before we can write applets like in the demos Cover many of same techniques Upcoming program Create an applet to display &quot;Welcome to Java Programming!&quot; Show applet and HTML file, then discuss them line by line
  • 41. Java applet Program Output 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.JApplet; // import class JApplet 9 10 public class WelcomeApplet extends JApplet { 11 12 // draw text on applet’s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super .paint( g ); 17 18 // draw a String at x-coordinate 25 and y-coordinate 25 19 g.drawString( &quot;Welcome to Java Programming!&quot; , 25 , 25 ); 20 21 } // end method paint 22 23 } // end class WelcomeApplet import allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends allows us to inherit the capabilities of class JApplet . Method paint is guaranteed to be called in all applets. Its first line must be defined as above.
  • 42. 3.3 A Simple Java Applet: Drawing a String Comments Name of source code and description of applet Import predefined classes grouped into packages import statements tell compiler where to locate classes used When you create applets, import the JApplet class (package javax.swing ) import the Graphics class (package java.awt ) to draw graphics Can draw lines, rectangles ovals, strings of characters import specifies directory structure 5 import java.awt.Graphics; // import class Graphics 8 import javax.swing.JApplet; // import class JApplet // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java.
  • 43. 3.3 A Simple Java Applet: Drawing a String Applets have at least one class definition (like applications) Rarely create classes from scratch Use pieces of existing class definitions Inheritance - create new classes from old ones (ch. 15) Begins class definition for class WelcomeApplet Keyword class then class name extends followed by class name Indicates class to inherit from ( JApplet ) JApplet : superclass (base class) WelcomeApplet : subclass (derived class) WelcomeApplet now has methods and data of JApplet 10 public class WelcomeApplet extends JApplet {
  • 44. 3.3 A Simple Java Applet: Drawing a String Class JApplet defined for us Someone else defined &quot;what it means to be an applet&quot; Applets require over 200 methods! extends JApplet Inherit methods, do not have to define them all Do not need to know every detail of class JApplet 10 public class WelcomeApplet extends JApplet {
  • 45. 3.3 A Simple Java Applet: Drawing a String Class WelcomeApplet is a blueprint appletviewer or browser creates an object of class WelcomeApplet Keyword public required File can only have one public class public class name must be file name 10 public class WelcomeApplet extends JApplet {
  • 46. 3.3 A Simple Java Applet: Drawing a String Our class inherits method paint from JApplet By default, paint has empty body Override (redefine) paint in our class Methods paint , init , and start Guaranteed to be called automatically Our applet gets &quot;free&quot; version of these by inheriting from JApplet Free versions have empty body (do nothing) Every applet does not need all three methods Override the ones you need Applet container “draws itself” by calling method paint 13 public void paint( Graphics g )
  • 47. 3.3 A Simple Java Applet: Drawing a String Method paint Lines 13-21 are the definition of paint Draws graphics on screen void indicates paint returns nothing when finishes task Parenthesis define parameter list - where methods receive data to perform tasks Normally, data passed by programmer, as in JOptionPane.showMessageDialog paint gets parameters automatically Graphics object used by paint Mimic paint 's first line 13 public void paint( Graphics g )
  • 48. 3.3 A Simple Java Applet: Drawing a String Calls version of method paint from superclass JApplet Should be first statement in every applet’s paint method Body of paint Method drawString (of class Graphics ) Called using Graphics object g and dot operator ( . ) Method name, then parenthesis with arguments First argument: String to draw Second: x coordinate (in pixels) location Third: y coordinate (in pixels) location Java coordinate system Measured in pixels (picture elements) Upper left is ( 0 , 0 ) 16 super .paint( g ); 19 g.drawString( &quot;Welcome to Java Programming!&quot; , 25 , 25 );
  • 49. 3.3.1 Compiling and Executing WelcomeApplet Running the applet Compile javac WelcomeApplet.java If no errors, bytecodes stored in WelcomeApplet.class Create an HTML file Loads the applet into appletviewer or a browser Ends in .htm or .html To execute an applet Create an HTML file indicating which applet the browser (or appletviewer ) should load and execute
  • 50. 3.3.1 Compiling and Executing WelcomeApplet Simple HTML file ( WelcomeApplet.html ) Usually in same directory as .class file Remember, .class file created after compilation HTML codes (tags) Usually come in pairs Begin with < and end with > Lines 1 and 4 - begin and end the HTML tags Line 2 - begins <applet> tag Specifies code to use for applet Specifies width and height of display area in pixels Line 3 - ends <applet> tag 1 <html> 2 <applet code = &quot;WelcomeLines.class&quot; width = &quot;300&quot; height = &quot;40&quot; > 3 </applet> 4 </html>
  • 51. 3.3.1 Compiling and Executing WelcomeApplet appletviewer only understands <applet> tags Ignores everything else Minimal browser Executing the applet appletviewer WelcomeApplet.html Perform in directory containing .class file 1 <html> 2 <applet code = &quot;WelcomeLines.class&quot; width = &quot;300&quot; height = &quot;40&quot; > 3 </applet> 4 </html>
  • 52. 3.4 Two More Simple Applets: Drawing Strings and Lines More applets First example Display two lines of text Use drawString to simulate a new line with two drawString statements Second example Method g.drawLine(x1, y1, x2, y2 ) Draws a line from ( x1 , y1 ) to ( x2 , y2 ) Remember that ( 0 , 0 ) is upper left Use drawLine to draw a line beneath and above a string
  • 53. 1 // Fig. 3.8: WelcomeApplet2.java 2 // Displaying multiple strings in an applet. 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.JApplet; // import class JApplet 9 10 public class WelcomeApplet2 extends JApplet { 11 12 // draw text on applet’s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super .paint( g ); 17 18 // draw two Strings at different locations 19 g.drawString( &quot;Welcome to&quot; , 25 , 25 ); 20 g.drawString( &quot;Java Programming!&quot; , 25 , 40 ); 21 22 } // end method paint 23 24 } // end class WelcomeApplet2 1. import 2. Class WelcomeApplet2 ( extends JApplet ) 3. paint 3.1 drawString 3.2 drawString on same x coordinate, but 15 pixels down The two drawString statements simulate a newline. In fact, the concept of lines of text does not exist when drawing strings.
  • 54. HTML file Program Output 1 <html> 2 <applet code = &quot;WelcomeApplet2.class&quot; width = &quot;300&quot; height = &quot;60&quot; > 3 </applet> 4 </html>
  • 55. WelcomeLines.java 2. Class WelcomeLines ( extends JApplet ) 3. paint 3.1 drawLine 3.2 drawLine 3.3 drawString Program Output 1 // Fig. 3.10: WelcomeLines.java 2 // Displaying text and lines 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.JApplet; // import class JApplet 9 10 public class WelcomeLines extends JApplet { 11 12 // draw lines and a string on applet’s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super .paint( g ); 17 18 // draw horizontal line from (15, 10) to (210, 10) 19 g.drawLine( 15 , 10 , 210 , 10 ); 20 21 // draw horizontal line from (15, 30) to (210, 30) 22 g.drawLine( 15 , 30 , 210 , 30 ); 23 24 // draw String between lines at location (25, 25) 25 g.drawString( &quot;Welcome to Java Programming!&quot; , 25 , 25 ); 26 27 } // end method paint 28 29 } // end class WelcomeLines Draw horizontal lines with drawLine (endpoints have same y coordinate).
  • 56. HTML file 1 <html> 2 <applet code = &quot;WelcomeLines.class&quot; width = &quot;300&quot; height = &quot;40&quot; > 3 </applet> 4 </html>
  • 57. 3.4 Two More Simple Applets: Drawing Strings and Lines Method drawLine of class Graphics Takes as arguments Graphics object and line’s end points X and y coordinate of first endpoint X and y coordinate of second endpoint
  • 58. 3.5 Another Java Applet: Adding Floating-Point Numbers Next applet Mimics application for adding two integers (Fig 2.9) This time, use floating point numbers (numbers with a decimal point) Using primitive data types Double – double precision floating-point numbers Float – single precision floating-point numbers Show program, then discuss
  • 59. AdditionApplet.java 1. import 2. Class AdditionApplet ( extends JApplet ) 3. Instance variable 4. init 4.1 Declare variables 4.2 showInputDialog 4.3 parseDouble 1 // Fig. 3.12: AdditionApplet.java 2 // Adding two floating-point numbers. 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.*; // import package javax.swing 9 10 public class AdditionApplet extends JApplet { 11 double sum; // sum of values entered by user 12 13 // initialize applet by obtaining values from user 14 public void init () 15 { 16 String firstNumber; // first string entered by user 17 String secondNumber; // second string entered by user 18 double number1; // first number to add 19 double number2; // second number to add 20 21 // obtain first number from user 22 firstNumber = JOptionPane.showInputDialog( 23 &quot;Enter first floating-point value&quot; ); 24 25 // obtain second number from user 26 secondNumber = JOptionPane.showInputDialog( 27 &quot;Enter second floating-point value&quot; ); 28 29 // convert numbers from type String to type double 30 number1 = Double.parseDouble( firstNumber ); 31 number2 = Double.parseDouble( secondNumber ); 32 2 // Adding two floating-point numbers 3 import java.awt.Graphics; // import class Graphics 5 6 public class AdditionApplet extends JApplet { 7 double sum; // sum of the values entered by the user 8 9 public void init() 10 { 11 String firstNumber, // first string entered by user 12 secondNumber; // second string entered by user 13 double number1, // first number to add 14 number2; // second number to add 15 16 // read in first number from user 17 firstNumber = 18 JOptionPane.showInputDialog( 19 &quot;Enter first floating-point value&quot; ); 20 21 // read in second number from user 22 secondNumber = 23 JOptionPane.showInputDialog( 24 &quot;Enter second floating-point value&quot; ); 25 26 27 // convert numbers from type String to type double * allows any class in the the package to be used. Instance variable sum may be used anywhere in the class, even in other methods. Data type double can store floating point numbers.
  • 60. 5. Draw applet contents 5.1 Draw a rectangle 5.2 Draw the results HTML file 33 // add numbers 34 sum = number1 + number2; 35 } 36 37 // draw results in a rectangle on applet’s background 38 public void paint( Graphics g ) 39 { 40 // call inherited version of method paint 41 super .paint( g ); 42 43 // draw rectangle starting from (15, 10) that is 270 44 // pixels wide and 20 pixels tall 45 g.drawRect( 15 , 10 , 270 , 20 ); 46 47 // draw results as a String at (25, 25) 48 g.drawString( &quot;The sum is &quot; + sum, 25 , 25 ); 49 50 } // end method paint 51 52 } // end class AdditionApplet 1 <html> 2 <applet code = &quot;WelcomeLines.class&quot; width = &quot;300&quot; height = &quot;40&quot; > 3 </applet> 4 </html> 31 // add the numbers 32 sum = number1 + number2; 33 } 34 35 public void paint( Graphics g ) 36 { 37 // draw the results with g.drawString 38 g.drawRect( 15, 10, 270, 20 ); 39 g.drawString( &quot;The sum is &quot; + sum, 25, 25 ); 40 } 41 } 1 <html> 2 <applet code=&quot;AdditionApplet.class&quot; width=300 height=50> 3 </applet> 4 </html> drawRect takes the upper left coordinate, width, and height of the rectangle to draw.
  • 62. 3.5 Another Java Applet: Adding Floating-Point Numbers Lines 1-2: Comments Line 5: import s class Graphics import not needed if use full package and class name public void paint ( java.awt.Graphics g ) Line 8: specify entire javax.swing package * indicates all classes in javax.swing are available Includes JApplet and JOptionPane Use JOptionPane instead of javax.swing.JOptionPane * does not not load all classes Compiler only loads classes it uses 5 import java.awt.Graphics; 8 import javax.swing.*;
  • 63. 3.5 Another Java Applet: Adding Floating-Point Numbers Begin class definition Inherit from JApplet , import ed from package javax.swing Instance variable declaration Each object of class gets own copy of the instance variable Declared in body of class, but not inside methods Variables declared in methods are local variables Can only be used in body of method Instance variables can be used anywhere in class Have default value ( 0.0 in this case) 10 public class AdditionApplet extends JApplet { 11 double sum; // sum of values entered by user
  • 64. 3.5 Another Java Applet: Adding Floating-Point Numbers Primitive data type double Used to store floating point (decimal) numbers Method init Normally initializes instance variables and applet class Guaranteed to be first method called in applet First line must always appear as above Returns nothing ( void ), takes no arguments Begins body of method init 11 double sum; // sum of values entered by user 14 public void init () 15 {
  • 65. 3.5 Another Java Applet: Adding Floating-Point Numbers Declare variables Two types of variables Reference variables (called references) Refer to objects (contain location in memory) Objects defined in a class definition Can contain multiple data and methods paint receives a reference called g to a Graphics object Reference used to call methods on the Graphics object Primitive data types (called variables) Contain one piece of data 16 String firstNumber; // first string entered by user 17 String secondNumber; // second string entered by user 18 double number1; // first number to add 19 double number2; // second number to add
  • 66. 3.5 Another Java Applet: Adding Floating-Point Numbers Distinguishing references and variables If data type is a class name, then reference String is a class firstNumber , secondNumber If data type a primitive type, then variable double is a primitive data type number1 , number2 16 String firstNumber; // first string entered by user 17 String secondNumber; // second string entered by user 18 double number1; // first number to add 19 double number2; // second number to add
  • 67. 3.5 Another Java Applet: Adding Floating-Point Numbers Method JOptionPane.showInputDialog Prompts user for input with string Enter value in text field, click OK If not of correct type, error occurs In Chapter 14 learn how to deal with this Returns string user inputs Assignment statement to string Lines 26-27: As above, assigns input to secondNumber 22 firstNumber = JOptionPane.showInputDialog( 23 &quot;Enter first floating-point value&quot; );
  • 68. 3.5 Another Java Applet: Adding Floating-Point Numbers static method Double.parseDouble Converts String argument to a double Returns the double value Remember static method syntax ClassName.methodName( arguments ) Assignment statement sum an instance variable, can use anywhere in class Not defined in init but still used 34 sum = number1 + number2; 30 number1 = Double.parseDouble( firstNumber ); 31 number2 = Double.parseDouble( secondNumber );
  • 69. 3.5 Another Java Applet: Adding Floating-Point Numbers Ends method init appletviewer (or browser) calls inherited method start start usually used with multithreading Advanced concept, in Chapter 15 We do not define it, so empty definition in JApplet used Next, method paint called Method drawRect( x1, y1, width, height ) Draw rectangle, upper left corner ( x1, y1 ), specified width and height Line 45 draws rectangle starting at (15, 10) with a width of 270 pixels and a height of 20 pixels 33 } 45 g.drawRect( 15 , 10 , 270 , 20 );
  • 70. 3.5 Another Java Applet: Adding Floating-Point Numbers Sends drawString message (calls method) to Graphics object using reference g &quot;The sum is&quot; + sum - string concatenation sum converted to a string sum can be used, even though not defined in paint Instance variable, can be used anywhere in class Non-local variable 48 g.drawString( &quot;The sum is &quot; + sum, 25 , 25 );
  • 71. 3.6 Viewing Applets in a Web Browser Applets can execute on Java-enabled browsers Many different browser version supporting different Java version specifications Some support for Java 1.0, many for Java 1.1 inconsistently Netscape Navigator 6 supports Java 2 (section 3.6.1) Use Java Plug-in to execute Java 2 applets on other browsers (section 3.6.2)
  • 72. Fonts By default, strings are drawn using the default font, plain style and default font size. To change the font, style or size, we need to create an object of class java.awt.Font and pass it to the setFont() method of the graphics object used in the paint() method. To create such a Font object, we need to specify the following parameters: The font name. The Style (Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Font.ITALIC). The font size. The font name can be the name of any font available on the particular computer (such as: TimesRoman, Courier, Helvetica etc.,) or any of the logical names shown in the table below: A screen font suitable for user input in text fields DialogInput A screen font suitable for labels in dialogs Dialog A font in which all characters have the same width. e.g. Courier Monospaced A font without small segments, e.g. Helvetica SansSerif A font with small segments at the end, e.g. Times New Roman Serif
  • 73. Fonts (cont’d) Example: The following applet displays the word Applet in large SansSerif font. import java.applet.*; import java.awt.*; public class BigFontApplet extends Applet{ public void paint(Graphics g){ final int SIZE = 48; Color myColor = new Color(0.25F, 0.5F, 0.75F); Font myFont = new Font(&quot;SansSerif&quot;, Font.BOLD, SIZE); g.setColor(myColor); g.setFont(myFont); g.drawString(&quot;Applet&quot;,5,60); } }
  • 74. Fonts (cont’d) If an applet will use several fonts , it is good to create the font objects in the init() method: import java.applet.*; import java.awt.*; public class FontExamples extends Applet{ private Font f, fb, fi, fbi; public void init() { setBackground(Color.yellow); f = new Font(&quot;TimesRoman&quot;, Font.PLAIN, 18); fb = new Font(&quot;Courier&quot;, Font.BOLD, 20); fi = new Font(&quot;TimesRoman&quot;, Font.ITALIC, 18); fbi = new Font(&quot;Helvetica&quot;, Font.BOLD + Font.ITALIC, 25); } public void paint(Graphics g){ g.setColor(Color.blue); g.setFont(f); g.drawString(&quot;This is TimesRoman plain font&quot;, 10, 25); //... } }
  • 75. Drawing in an Applet import java.applet.Applet; import java.awt.*; // assume that the drawing area is 150 by 150 public class SquareAndRectangle extends Applet { final int areaSide = 150 ; final int width = 100, height = 50; public void paint ( Graphics gr ) { setBackground( Color.green ); gr.setColor( Color.red ); // outline the drawing area gr.drawRect( 0, 0, areaSide-1, areaSide-1 ); // draw interiour rectange. gr.drawRect( areaSide/2 - width/2 , areaSide/2 - height/2, width, height ); } }
  • 76. Java’s coordinate system Java uses an (x, y) coordinate system (0, 0) is the top left corner (50, 0) is 50 pixels to the right of (0, 0) (0, 20) is 20 pixels down from (0, 0) (w - 1, h - 1) is just inside the bottom right corner, where w is the width of the window and h is its height (0, 0) (0, 20) (50, 0) (50, 20) (w-1, h-1) (50, 0) (0, 0) (0, 20) (50, 20)
  • 77. Drawing rectangles There are two ways to draw rectangles: g.drawRect( left , top , width , height ); g.fillRect( left , top , width , height );
  • 78. Drawing strings A String is a sequence of characters enclosed in double quote marks &quot;Hello, World!&quot; A double quote mark in a String must be preceded by a backslash ( \ ) &quot;He said, \&quot;Please don't go!\&quot; &quot; To draw a string, you need to specify not only what you want to say, but where to say it g.drawString( string , left , top ); For example, g.drawString(&quot;Example JApplet&quot;, 20, 80);
  • 79. The complete applet import javax.swing.JApplet; import java.awt.*; // CIT 591 example public class Drawing extends JApplet { public void paint(Graphics g) { g.setColor(Color.BLUE); g.fillRect(20, 20, 50, 30); g.setColor(Color.RED); g.fillRect(50, 30, 50, 30); g.setColor(Color.BLACK); g.drawString(&quot;Example JApplet&quot;, 20, 80); } }
  • 80. More java.awt.Graphics methods g.drawLine( x1 , y1 , x2 , y2 ); g.drawOval( left , top , width , height ); g.fillOval( left , top , width , height ); g.drawRoundRect( left , top , width , height, arcWidth , arcHeight ); arcWidth , arcHeight define the “roundedness” of corners g.fillRoundRect( left , top , width , height, arcWidth , arcHeight ); g.drawArc( left , top , width , height , startAngle , arcAngle ); Angles are in degrees 0 degrees is the 3 o’clock position Positive angles are to the right g.FillArc( left , top , width , height , startAngle , arcAngle );
  • 81. Still more Graphics methods g.drawPolygon( xPoints , yPoints , n ); g.fillPolygon( xPoints , yPoints , n ); xPoints and yPoints are int arrays of size n One way to write an int array is: new int[] { value1 , value2 , ..., valueN } Example: g.drawPolygon(new int[] { 250, 290, 210 },                    new int[] { 210, 290, 290 }, 3); draws a triangle using the 3 points (250, 210), (290, 290), and (210, 290). g.drawPolyline( xPoints , yPoints , n ); A “polyline” is like a polygon, except the first and last points are not automatically connected Hence, there is no “fillPolyline” method
  • 82. The HTML page You can only run an applet from an HTML page The HTML looks something like this: <html> <body> <h1>Drawing Applet</h1> <applet code=&quot;Drawing.class&quot; width=&quot;100&quot; height=&quot;150&quot;> </applet> </body> </html> Eclipse will create this HTML for you You don’t even need to think about the HTML just yet
  • 83. Other useful JApplet methods System.out.println(String s ) Works from appletviewer , not from browsers Automatically opens an output window. showStatus(String s ) displays the String in the applet’s status line. Each call overwrites the previous call. You have to allow time to read the line!