computer science [3] java programming ii - laboratory course lab 6: introduction to java applets...

18
Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Course Laboratory Course Lab 6: Lab 6: Introduction to Java Applets Introduction to Java Applets Sample Applets from the Java Sample Applets from the Java Simple Java Applet: Drawing a String & Simple Java Applet: Drawing a String & Lines Lines Faculty of Engineering & IT Software Engineering Department WWW.PALINFONET.COM Eng.Omar Al-Nahal

Upload: anastasia-mason

Post on 26-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Laboratory

Course Course

Lab 6:Lab 6:Introduction to Java AppletsIntroduction to Java Applets

Sample Applets from the Java Sample Applets from the Java Simple Java Applet: Drawing a String & LinesSimple Java Applet: Drawing a String & Lines

Faculty of Engineering & ITSoftware Engineering Department

WWW.PALINFONET.COMWWW.PALINFONET.COM

Eng.Omar Al-Nahal

Eng.Omar Al-Nahal

Page 2: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Introduction to Java AppletsIntroduction to Java Applets

Applets , Web page , Client , Server

< a pple t co de = H e llo W o rld.c la s s < /a pple t>......

H e llo W o rld.c la s s

s e r ve r ho s t

we b s e rv e r

m y W e bPa g e .h tm l

br o w s e r ho s t

bro ws e r re qe u s t fo rm y W e bPa g e .h tm l

m y W e bPa g e .h tm l

re qu e s t fo rH e llo W o rldcla s s

H e llo W o rld.c la s s

H e llo W o rld.c la s s

Page 3: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Introduction to Java AppletsIntroduction to Java Applets

AppletApplet• Program that runs in Program that runs in

– appletviewerappletviewer (test utility for applets) (test utility for applets)

– Web browser (IE, Communicator)Web browser (IE, Communicator)

• Executes when HTML document containing applet is openedExecutes when HTML document containing applet is opened

Sample AppletsSample Applets• Provided in Java 2 Software Development Kit (J2SDK)Provided in Java 2 Software Development Kit (J2SDK)

• Source code included (Source code included (.java.java files) files)

Running appletsRunning applets• In command prompt, change to subdirectory of applet In command prompt, change to subdirectory of applet cdcd directoryNamedirectoryName• There will be an HTML file used to execute appletThere will be an HTML file used to execute applet type type appletviewer example1.htmlappletviewer example1.html• Applet will run, Applet will run, ReloadReload and and QuitQuit commands under commands under AppletApplet menu menu

Page 4: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

A Simple Java Applet: Drawing a StringA Simple Java Applet: Drawing a String

Create our own appletCreate our own applet• Print Print "Welcome to Java Programming!""Welcome to Java Programming!"• import javax.swing.JAppletimport javax.swing.JApplet

– Needed for all appletsNeeded for all applets

• import java.awt.Graphicsimport java.awt.Graphics– Allows program to draw graphics (lines,text) on an appletAllows program to draw graphics (lines,text) on an applet

• Like applications, applets have at least one class definitionLike applications, applets have at least one class definition

Rarely create applets from scratchRarely create applets from scratch• Use of class existing definitionsUse of class existing definitionspublic class WelcomeApplet extends JApplet {public class WelcomeApplet extends JApplet {• extends ClassName extends ClassName - class to inherit from- class to inherit from

– In this case, inherit from class In this case, inherit from class JAppletJApplet

Page 5: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

A Simple Java Applet: Drawing a StringA Simple Java Applet: Drawing a String

ClassesClasses• Templates/blueprints create or instantiate objects Templates/blueprints create or instantiate objects

– Objects - locations in memory to store dataObjects - locations in memory to store data

– Implies that data and methods associated with objectImplies that data and methods associated with object

MethodsMethods• paintpaint, , initinit, and , and startstart called automatically for all applets called automatically for all applets

– Get "free" version when you inherit from JAppletGet "free" version when you inherit from JApplet

– By default, have empty bodiesBy default, have empty bodies

Page 6: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

A Simple Java Applet: Drawing a StringA Simple Java Applet: Drawing a String

Method Method paintpaint• Used to draw graphics, define:Used to draw graphics, define:

public void paint( Graphics g )public void paint( Graphics g )– Takes a Takes a GraphicsGraphics object object gg as a parameter as a parameter

– For now, all method definitions begin with publicFor now, all method definitions begin with public

• Call methods of object Call methods of object gg to draw on applet to draw on appletdrawString("String to draw", x, y);drawString("String to draw", x, y);– Draws Draws "String to draw""String to draw" at location ( at location (xx,,yy))

– Coordinates specify bottom left corner of stringCoordinates specify bottom left corner of string

– ((00, , 00) is upper left corner of screen) is upper left corner of screen

– Measured in pixels (picture elements)Measured in pixels (picture elements)

Page 7: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

A Simple Java Applet: Drawing a StringA Simple Java Applet: Drawing a String

Create the HTML file (Create the HTML file (.html.html or or .htm).htm)• Many HTML codes (tags) come in pairsMany HTML codes (tags) come in pairs

<myTag> ... </myTag><myTag> ... </myTag>• Create Create <HTML><HTML> tags with tags with <applet><applet> tags inside tags inside• appletviewerappletviewer only understands only understands <applet><applet> tags tags

– Minimal browserMinimal browser– Specify complied Specify complied .class.class file, width, and height of applet (in pixels) file, width, and height of applet (in pixels)<applet code = "WelcomeApplet.class" width = 300<applet code = "WelcomeApplet.class" width = 300 height = 30> height = 30>

– Close tag with Close tag with </applet></applet>

Running the appletRunning the appletappletviewer WelcomeApplet.htmlappletviewer WelcomeApplet.html

Page 8: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

1 // Fig. 24.13: WelcomeApplet.java

2 // A first applet in Java

3 import javax.swing.JApplet; // import class JApplet

4 import java.awt.Graphics; // import class Graphics

5

6 public class WelcomeApplet extends JApplet {

7 public void paint( Graphics g )

8 {

9 g.drawString( "Welcome to Java Programming!", 25, 25 );

10 }

11 }

1 <html>

2 <applet code="WelcomeApplet.class" width=300 height=30>

3 </applet>

4 </html>4 </html>

Example – Welcome Applet

super.paint( g (

Page 9: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Two More Simple Applets: Drawing Strings and Lines

Other methods of class Other methods of class GraphicsGraphics• No concept of lines of text, as in No concept of lines of text, as in System.out.printlnSystem.out.println when when

drawing graphicsdrawing graphics

• To print multiple lines, use multiple To print multiple lines, use multiple drawStringdrawString calls calls• drawLine( x1, y1, x2, y2 ) ;drawLine( x1, y1, x2, y2 ) ;

– Draws a line from ( Draws a line from ( x1x1, , y1y1 ) to ( ) to ( x2x2, , y2y2 ) )

Page 10: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

1 // Fig. 24.17: WelcomeLines.java

2 // Displaying text and lines

3 import javax.swing.JApplet; // import class JApplet

4 import java.awt.Graphics; // import class Graphics

5

6 public class WelcomeLines extends JApplet {

7 public void paint( Graphics g )

8 {

9 g.drawLine( 15, 10, 210, 10 );

10 g.drawLine( 15, 30, 210, 30 );

11 g.drawString( "Welcome to Java Programming!", 25, 25 );

12 }

13 }

Simple Applets: Drawing Strings and Lines

super.paint( g (

Page 11: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Another Java Applet: Adding IntegersAnother Java Applet: Adding Integers

Next applet mimics program to add two integersNext applet mimics program to add two integers• This time, use floating point numbersThis time, use floating point numbers

– Can have decimal point, Can have decimal point, 6.76026.7602– float float - single precision floating point number .- single precision floating point number .– doubledouble - approximately double precision floating point number. - approximately double precision floating point number.

– Uses more memoryUses more memory

• Use Use showInputDialogshowInputDialog to get input, as before to get input, as before

• Use Use Double.parseDouble( String)Double.parseDouble( String)– Converts a Converts a StringString to a to a doubledouble

Page 12: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Another Java Applet: Adding IntegersAnother Java Applet: Adding Integers

importimport statements statements• Not necessary if specify full class name every time neededNot necessary if specify full class name every time needed

public void paint( java.awt.Graphics g)public void paint( java.awt.Graphics g)• ** - indicates all classes in package should be available - indicates all classes in package should be available

– import java.swing.*;import java.swing.*;– Recall that this contains Recall that this contains JAppletJApplet and and JOptionPaneJOptionPane

– Does not import subdirectoriesDoes not import subdirectories

Instance variablesInstance variables• Variables declared in body of a class (not in a method)Variables declared in body of a class (not in a method)

– Each object of class gets its own copyEach object of class gets its own copy

– Can be used inside any method of the classCan be used inside any method of the class

• Before, variables declared in Before, variables declared in mainmain– Local variables, known only in body of method definedLocal variables, known only in body of method defined

Page 13: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Another Java Applet: Adding IntegersAnother Java Applet: Adding Integers

Instance variablesInstance variables• Have default valuesHave default values

– Local variables do not, and require initialization before useLocal variables do not, and require initialization before use

– Good practice to initialize instance variables anywayGood practice to initialize instance variables anyway

Method Method initinit• Called automatically in all appletsCalled automatically in all applets

• Commonly used to initialize variablesCommonly used to initialize variables

public void init()public void init()

ReferencesReferences• Identifiers (such as Identifiers (such as myStringmyString) refer to objects ) refer to objects

– Contain locations in memoryContain locations in memory

• References used to call methods, i.e. References used to call methods, i.e. g.drawStringg.drawString

Page 14: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Another Java Applet: Adding IntegersAnother Java Applet: Adding Integers

Variables vs. ObjectsVariables vs. Objects• VariablesVariables

– Defined by a primitive data typeDefined by a primitive data type– charchar, , bytebyte, , shortshort, , intint, , longlong, , floatfloat, , doubledouble, , booleanboolean– Store one value at a timeStore one value at a time

– Variable Variable myIntmyInt

• Objects defined in classesObjects defined in classes– Can contain primitive (built-in) data typesCan contain primitive (built-in) data types

– Can contain methodsCan contain methods– GraphicsGraphics object object gg

• If data type a class name, then identifier is a referenceIf data type a class name, then identifier is a reference– Otherwise, identifier is a variableOtherwise, identifier is a variable

Page 15: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Another Java Applet: Adding IntegersAnother Java Applet: Adding Integers

Other methods of class Other methods of class GraphicsGraphics• drawRect( x1, y1, x2, y2 );drawRect( x1, y1, x2, y2 );• Draws a rectangle with upper-left corner ( Draws a rectangle with upper-left corner ( x1x1, , y1y1 ), and lower right ), and lower right

corner (corner (x2,x2, y2y2 ) )

Page 16: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

1 // Fig. 24.19: AdditionApplet.java2 // Adding two floating-point numbers3 import java.awt.Graphics; // import class Graphics4 import javax.swing.*; // import package javax.swing56 public class AdditionApplet extends JApplet {7 double sum; // sum of the values entered by the user89 public void init()10 {11 String firstNumber, // first string entered by user12 secondNumber; // second string entered by user13 double number1, // first number to add14 number2; // second number to add1516 // read in first number from user17 firstNumber =18 JOptionPane.showInputDialog(19 "Enter first floating-point value" );2021 // read in second number from user22 secondNumber =23 JOptionPane.showInputDialog(24 "Enter second floating-point value" );2526 // convert numbers from type String to type double27 number1 = Double.parseDouble( firstNumber ); 28 number2 = Double.parseDouble( secondNumber );2930 // add the numbers

Example : Addition Applet

Page 17: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

31 sum = number1 + number2;

32 }

33

34 public void paint( Graphics g )

35 {

36 // draw the results with g.drawString

37 g.drawRect( 15, 10, 270, 20 );

38 g.drawString( "The sum is " + sum, 25, 25 );

39 }

40 }

1 <html>

2 <applet code="AdditionApplet.class" width=300 height=50>

3 </applet>

4 </html>4 </html>

Example : Addition Applet

super.paint( g );

Page 18: Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing

Program OutputProgram Output