Top Banner
Lesson 3 CSS 161A ECC © Niko Čulevski 1 Lesson #3 – Applets 3.0 Introduction. Most of you are familiar with the Internet and with the World Wide Web (WWW). Browsers such as Netscape and Internet Explorer allow you to view home Web pages on other computers by requesting a server to provide to you (the client) a copy of the hypertext markup language (HTML) file. You locate the server by its uniform resource locator (URL) address. Unlike a Java application that executes from a command window, an applet is a Java program that runs in the appletviewer (a test utility for applets that is included with the J2SDK) or a World Wide Web browser such as Netscape Communicator or Microsoft Internet Explorer. The appletviewer (or browser) executes an applet when a Hypertext Markup Language (HTML) document containing the applet is opened in the appletviewer (or browser). 3.1 HTML. An HTML program/file is a sequence of three kinds of tokens: (1) ordinary text characters, (2) tags, and (3) special symbols. 3.1.1 The entire html document is surrounded by the <HTML> and </HTML> tags. Tags usually are paired are special instructions to the browser and often have attributes. For example, the <BODY> tag has background color, links color, etc., attributes. 3.1.2 There are many tags in HTML. For us, the crucial ones are <APPLET> and </APPLET>. Typically, the <APPLET> tag has three attributes: code, width, and height. For example, code = “Hello.class”, width = 300, height = 100 indicates to the appletviewer the name of the applet, and the size of the panel to use, in pixels. 3.1.3 Other APPLET attributes include: 3.1.3.1 ALIGN—used to align the applet with the following values: 3.1.3.1.1 LEFT—place applet at the left margin. Here is an example: <APPLET CODE="HelloApplet.class" WIDTH=100 HEIGHT=50 ALIGN = left> </APPLET> 3.1.3.1.2 RIGHT-- place applet at the left margin. Here is an example: <APPLET CODE="HelloApplet.class" WIDTH=100 HEIGHT=50 ALIGN = right>
18
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Lesson 3 CSS 161A

    ECC Niko ulevski 1

    Lesson #3 Applets

    3.0 Introduction. Most of you are familiar with the Internet and with the World Wide Web (WWW). Browsers such as Netscape and Internet Explorer allow you to view home Web pages on other computers by requesting a server to provide to you (the client) a copy of the hypertext markup language (HTML) file. You locate the server by its uniform resource locator (URL) address. Unlike a Java application that executes from a command window, an applet is a Java program that runs in the appletviewer (a test utility for applets that is included with the J2SDK) or a World Wide Web browser such as Netscape Communicator or Microsoft Internet Explorer. The appletviewer (or browser) executes an applet when a Hypertext Markup Language (HTML) document containing the applet is opened in the appletviewer (or browser).

    3.1 HTML. An HTML program/file is a sequence of three kinds of tokens: (1) ordinary text characters, (2) tags, and (3) special symbols.

    3.1.1 The entire html document is surrounded by the and tags. Tags usually are paired are special instructions to the browser and often have attributes. For example, the tag has background color, links color, etc., attributes.

    3.1.2 There are many tags in HTML. For us, the crucial ones are and . Typically, the tag has three attributes: code, width, and height. For example, code = Hello.class, width = 300, height = 100 indicates to the appletviewer the name of the applet, and the size of the panel to use, in pixels.

    3.1.3 Other APPLET attributes include: 3.1.3.1 ALIGNused to align the applet with the following values:

    3.1.3.1.1 LEFTplace applet at the left margin. Here is an example:

    3.1.3.1.2 RIGHT-- place applet at the left margin. Here is an example:

  • Lesson 3 CSS 161A

    ECC Niko ulevski 2

    3.1.3.1.3 BASELINEThe bottom of the applet is aligned with the baseline of the text in which the applet appears.

    3.1.3.1.4 ABSMIDDLEThe middle of the applet is aligned with the middle of the largest item on the line on which the applet appears.

    3.1.3.1.5 MIDDLE-- The middle of the applet is aligned with the middle of the baseline of the text on the line on which the applet appears.

    3.1.3.1.6 ABSBOTTOMThe bottom of the applet is aligned with the lowest item in the line.

    3.1.3.1.7 BOTTOMSame as BASELINE alignment. 3.1.3.1.8 TEXTTOPThe top of the applet is aligned with the top of the

    tallest text in the line.

  • Lesson 3 CSS 161A

    ECC Niko ulevski 3

    3.1.3.1.9 TOPThe top of the applet is aligned with the top of the tallest item in the line. The tallest item could be text or another applet or image.

    3.1.3.2 HSPACEthe amount of horizontal space that a Web browser should put between the applet and any surrounding items, in pixels.

    3.1.3.3 VSPACE-- the amount of vertical space that a Web browser should put between the applet and any surrounding items, in pixels.

    3.1.3.4 CODEBASEspecifies the location (base URL, absolute or relative) of the applet.

    3.1.3.5 OBJECTname of a file that contains a serialized applet that is to be created by deserialization.

    3.1.3.6 ARCHIVEa comma separated list of JAR (Java Archive) files that are preloaded by the Web browser or applet viewer.

    3.1.3.7 NAMEgives a name to the applet instance. Useful for applets running simultaneously to communicate with each other.

    3.1.3.8 ALTtext to be displayed by browsers that understand the APPLET tag but do not support Java.

    3.2 Applets and the APPLET Tag. An applet is a Java program that must be run from another program, a host program, usually a browser. It is this browser that guarantees that the applet cannot store unwanted data on your machine and that it does not contain viruses. Every applet is implemented by creating a subclass of the Applet or JApplet class. The following figure shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what an applet can do. Running an applet makes an active Web page that is secure from virus attack. The steps for creating and viewing the applet are:

    3.2.1 Write the applet in Java. Note that applets have no main() method.

    3.2.2 Compile the *.java file to produce *.class bytecode with javac Hello.java.

    3.2.3 Create an HTML file that contains at least the following lines:

  • Lesson 3 CSS 161A

    ECC Niko ulevski 4

    3.2.4 View the applet either in your favorite browser or with appletviewer

    Hello.html. 3.2.5 Welcome to Java Programming Example.

    A Simple Java Applet: Printing a Line of Text.

    1 // A first program in Java 2 import java.applet.Applet; // import Applet class 3 import java.awt.Graphics; // import Graphics class 4 5 public class Welcome extends Applet { 6 public void paint( Graphics g ) 7 { 8 g.drawString( "Welcome to Java Programming!", 25, 25 ); 9 } 10 }

    3.2.5.1 The line numbers are not part of the source codethey are for convenient comment referencing.

    3.2.5.2 Line 1 begins with // indicating that the remainder of the line is a single-line comment and is neglected by the compiler. Comments document the program and improve readability of obtuse code.

    3.2.5.3 Lines 2 and 3 tell the compiler to find the required classes to compile the program. Class Applet is located in package java.applet and class Graphics is located in package java.awt.

    3.2.5.4 Line 5 begins a class definition for the Welcome class. Extends indicates that the derived class Welcome is inherited from the base class Applet The welcome class is used to create an object that executes the applet. The keyword public is required to enable the browser to create an instance of the applet and to execute it. Note the left braces, {, as a beginning of a block.

    3.2.5.5 The file name for the source code must match the name of the class (note that Java is case sensitive). Thus the source file must be Welcome.java.

    3.2.5.6 Line 6 is the beginning of the method paint (lines 6-9). Its job is to draw graphics on the screen. It requires a Graphics object g in its parameter list and it does not return any results when it completes its task; hence the keyword void.

    3.2.5.7 The left brace, {, on line 7 begins the method definitions body. The corresponding right brace, }, on line 9 ends the method definitions body.

    3.2.5.8 Line 8 instructs the computer to perform an action, namely to

  • Lesson 3 CSS 161A

    ECC Niko ulevski 5

    display Welcome to Java Programming! on the screen. Unlike method paint, the method drawstring defined by the class Graphics is not called automatically for you; rather, it is called using the Graphics object g followed by the dot operator. The three parameters of the method drawstring are a character string for the message, and the two coordinates, 25 and 25, at which the string should be drawn in the applets area on the screen. Coordinates are measured from the upper-left corner of the applet in pixels. Note that every statement must end with a semicolon.

    3.2.5.9 The MS-DOS command javac Welcome.java compiles the class Welcome and creates bytecodes in the file Welcome.class.

    3.2.5.10 To execute the Java applet create an HTML text file, Welcome.html defined as

    3.2.6 Another Java Applet: Adding Integers. The following applet inputs integers typed by a user and displays the sum.

    1 // Addition program 2 import java.applet.Applet; // import Applet class 3 import java.awt.*; // import the java.awt package 4 import java.awt.event.*; // import the java.awt.event package 5 6 public class Addition extends Applet implements ActionListener { 7 Label prompt; // message that prompts user to input 8 TextField input; // input values are entered here 9 int number; // variable that stores input value 10 int sum; // variable that stores sum of integers 11 12 // setup the graphical user interface components 13 // and initialize variables

  • Lesson 3 CSS 161A

    ECC Niko ulevski 6

    14 public void init() 15 { 16 prompt = new Label( "Enter integer and press Enter:" ); 17 add( prompt ); // put prompt on applet 18 19 input = new TextField( 10 ); 20 add( input ); // put input TextField on applet 21 22 sum = 0; // set sum to 0 23 24 // "this" applet handles action events for TextField input 25 input.addActionListener( this ); 26 } 27 28 // process user's action in TextField input 29 public void actionPerformed( ActionEvent e ) 30 { 31 // get the number and convert it to an integer 32 number = Integer.parseInt( e.getActionCommand() ); 33 34 sum = sum + number; // add number to sum 35 input.setText( "" ); // clear data entry field 36 showStatus( Integer.toString( sum ) ); // display sum 37 } 38 }

    3.2.6.1 Lines 2 through 4 specify the location of class Applet, entire java.awt package (TextField and Label classes are derived from it), and the entire java.awt.event package for processing the users interactions with the programs GUI.

    3.2.6.2 Line 6 says that class Addition inherits from Applet and implements ActionListener interface. The interface ActionListener specifies that this class must define a method with line 29.

    3.2.6.3 Lines 7 through 10 are declarations for displaying a message to the user (prompt of type Label, and for capturing the users input in a TextField named input. The variables number and sum are integer type with valid variable names.

  • Lesson 3 CSS 161A

    ECC Niko ulevski 7

    3.2.6.4 The applet contains two methods: init (line 14) and actionPerformed (line 29). Method init is a special method that initializes variables and references and is to be called in every applet. The predefined startup sequence of method calls made by the browser for every applet is always init, start, and paint. Your applet class gets a free version of each of these methods from the Applet class. But not every applet needs all three.

    3.2.6.5 Line 16 creates a label object with the new operator and initializes it with the string Enter integer and press Enter:.

    3.2.6.6 Line 17 places the Label GUI component prompt on the applet. 3.2.6.7 Line 19 creates a TextField object with 10 characters to be

    displayed and line 20 places the input object on the applet. 3.2.6.8 Line 22 initializes sum to 0 and line 25 specifies that this applet

    should listen for events from the TextField input. The this keyword enables the applet to refer to itself.

    3.2.6.9 Line 29 defines a public method that returns nothing (void). It receives one argument, an ActionEvent e whose method getActionCommand in line 32 will return the characters typed in the input TextField.

    3.2.6.10 Method Integer.parseInt is a special static method of class Integer that converts its String argument into an integer. Class Integer is part of the package java.lang, automatically imported in every Java program.

    3.2.6.11 The assignment statement in line 32 calculates the sum of the variables sum and number.

    3.2.6.12 Line 35 clears the input TextField with method setText and line 36 uses the Applets showStatus method to put a string (the converted sum to String) in the status bar.

    3.2.7 The Temperature Applet.

    import java.awt.*; import java.applet.*; import java.awt.event.*;

    public class TempApplet extends Applet implements ActionListener { Panel panF, panC; Label labF, labC; TextField textF, textC; Button convButton;

    public void init()

  • Lesson 3 CSS 161A

    ECC Niko ulevski 8

    { setLayout(new BorderLayout()); panF = new Panel(); panC = new Panel();

    labF = new Label("Fahr:"); panF.add(labF); //add to panel textF = new TextField(10); panF.add(textF); //add to panel add("North", panF); //add panel to applet

    labC = new Label("Cent:"); panC.add(labC); //add to panel textC = new TextField(10); panC.add(textC); //add to panel add("Center", panC); //add panel to applet

    convButton = new Button("Convert"); add("South", convButton);

    textF.addActionListener(this); textC.addActionListener(this); convButton.addActionListener(this); }

    public void actionPerformed(ActionEvent e) { if (e.getSource() == convButton||e.getSource() == textF) {Double temp = new Double(textF.getText()); double d = temp.doubleValue(); d = (d - 32.0)/1.8; textC.setText(String.valueOf(d)); } else {Double temp = new Double(textC.getText()); double d = temp.doubleValue(); d = 1.8*d + 32.0; textF.setText(String.valueOf(d)); }

  • Lesson 3 CSS 161A

    ECC Niko ulevski 9

    } }

    3.3 The Applet class. The Applet class is defined in the java.applet package (see

    http://java.sun.com/docs/books/tutorial/uiswing/start/swingApplet.html for swing applets). In fact it is the only class defined in that package. It is a subclass of the panel class, so applets are containers, similar to frames. As an instance of a user-defined subclass of the Applet class, an applet normally overrides or inherits one or more of the following methods:

    3.3.1 Applet.init()invoked automatically by the AWT run-time system when the applet is launched. Similar to a constructor, it is used for initialization. Note that the Web browser does not pass any arguments to an applets constructor method, so defining one is not too useful.

    3.3.2 Applet.start()--invoked automatically by the AWT whenever the HTML program is reloaded into the Web browser (Reload/Refresh/F5), i.e., when the applet become visible. Often used with animation and with threads.

    3.3.3 Applet.stop()invoked when the HTML page that contains the applet is left. The applet becomes temporarily invisible, as when the user has scrolled it off the screen.

    3.3.4 Applet.destroy()--invoked automatically by the AWT when the browser quits. The applet frees any resources and is unloaded from memory.

    3.3.5 Component.paint()--invoked automatically by the AWT whenever it detects that any part of the applet needs to be redrawn.

    3.3.6 Component.repaint()asks the AWT to redraw the frame. It calls update() which calls paint() to clear the panel by filling it with its background color and then repaints it. This causes flickering in animation. To overcome this flickering, override the update() method (shown later). The repaint method has four forms:

    3.3.6.1 public void repaint(); 3.3.6.2 public void repaint(long ms); 3.3.6.3 public void repaint(int x, int y, int width, int height); 3.3.6.4 public void repaint(long ms, int x, int y, int width, int height);

    3.3.7 getAppletInfo()called to get information about the applet. 3.3.8 getParameterInfo()--called to get information about the parameters the

    applet responds to.

  • Lesson 3 CSS 161A

    ECC Niko ulevski 10

    3.3.9 getAudioClip()loads a sound clip from the network and returns an AudioClip object.

    3.3.10 getParameter()looks up and returns the value of a named parameter.

    3.3.11 getCodeBase()returns the base URL from which the applet class was loaded.

    3.3.12 getDocumentBase-- returns the base URL of the HTML file that refers to the applet.

    3.3.13 showStatus()display a message in the status line of the browser or applet viewer.

    3.3.14 getAppletContextreturns the AppletContext object for the applet. 3.3.15 The Life Cycle of an Applet Example.

    // Example Life Cycle of an Applet

    import java.applet.Applet; import java.awt.*;

    public class LifeCycle extends Applet { int initCount=0; int startCount=0; int stopCount=0; int destroyCount=0; int startPaint=0;

    public void init() { ++initCount; System.out.println("init(): " + initCount); } public void start() { ++startCount; System.out.println("start() " + startCount); //picture above: started applet } //moved between tasks 4 times public void paint(Graphics g) { ++startPaint; System.out.println("paint() " + startPaint); for (int i = 0; i < 10 ; i++) g.drawString( "Welcome to Java Programming!", 25 + 3*i, 25 + 12*i ); }

  • Lesson 3 CSS 161A

    ECC Niko ulevski 11

    public void stop() { ++stopCount; System.out.println("stop() " + stopCount); }

    public void destroy() { ++destroyCount; System.out.println("destroy() " + destroyCount); }

    } //picture above after reloading applet: stop, destroy, init, start, paint sequence.

    //picture above after restart: stop, destroy, init, start, paint. Note count on last three!

    3.3.16 Passing Parameters to Applets. Applets can be customized by passing information called parameters to the applet. Parameters can be used to set colors, modify the behavior of the applet, or provide an applet with information to be displayed. The programmer of the applet should document the available parameters.

    3.3.17 ScrollText Example.

    Scrolling Text

  • Lesson 3 CSS 161A

    ECC Niko ulevski 12

    3.3.17.1 Note that the parameter names are case sensitive and that their values must be in quotes.

    3.3.17.2 Before you pass a parameter to an applet, you must know the name of the available parameters as well as the valid values.

    3.3.17.3 An optional alternate HTML code can reside between and tags for Java deficient browsers.

    3.4 The Java API. Javas application programming interface (API) consists of over 20 packages containing large collections (over several hundred) of classes, each with many methods, as well as some interfaces and exceptions.

    3.4.1. Partial list of useful predefined packages in Java (23 as of version 1.1) follows in the table below.

    Package Name Contents java.applet Classes for implementing applets. java.awt Classes for graphics, windows (cursors, scrolling, colors, clipping, and

    GUIs. java.awt.datatransfer Classes for intertransfer data transfer (clipboard). java.awt.event Classes that support AWT "delegation" event-handling model. Three major

    categories: (1) event classes, (2) event listeners, and (3) event adoptors. java.awt.image Clases for image processing. java.awt.image Classes for image management. java.awt.peer Interface definitions for platform-independent GUIs (pop-up menu and

    scrolling area).

  • Lesson 3 CSS 161A

    ECC Niko ulevski 13

    java.beans Classes for creating and using embeddable, reusable software components. Classes and interfaces in this package are used: (1) to create builder application tools, (2) to develop Java beans for use in such application builders, to develop applications that use Java beans.

    java.io Classes for input and output. By far the largest of the core Java packages, it contains byte stream and character stream I/O classes as well as reader and writer streams.

    java.lang Basic language classes like String and Math. No need to implicitly import it because it is the only package that is automatically imported in every Java program.

    java.lang.reflect Enables a Java program to examine the structure of Java classes and to reflect upon its own structure.

    java.math Beyond providing the main math functions and standard math constants, this package provides support for arithmetic on arbitrary-size integers and floating-point numbers.

    java.net Classes for networking (multicast and Unix-style sockets, etc.). java.rmi Classes for Remote Method Invocation. java.rmi.dgc Classes and interfaces required for distributed garbage collection java.rmi.registry Classes and interfaces required for a Java client to look up remote object

    by name java.rmi.server The largest of the rmi packages, it allows a Java program to create an

    object that can be used remotely by other Java programs.

    java.security Classes and interfaces that represent the fundamental abstractions of cryptographic security: public and private keys, certificates, message digests, and digital signatures.

    java.security.acl Defines low-level interfaces for controlling access control lists. java.security.interfaces Classes required for the Java Security APIs implementation-independent

    design java.sql The Java Database Connectivity (JDBC) API. java.text Classes and interfaces used for internationalization. java.util Useful auxiliary classes such as Date. java.util.zip Classes for computing checksums on streams of data, and for compressing

    and archiving streams of data.

    3.4.2 The java.awt package (awt is an acronym for abstract windowing toolkit) contains many graphics (windows, GUIs) classes which are used to create buttons (from Button class), labels, textfields, scroll bars, etc. The steps are:

    3.4.2.1 Create a button object: Button yesButton = new Button(Yes);

    3.4.2.2 Add the button to the applet in its init method: Add(YesButton); 3.4.3 The java.awt.event package contains classes for various types of events,

    such as clicking on a button.

  • Lesson 3 CSS 161A

    ECC Niko ulevski 14

    3.5 Running Applets Using the appletviewer. Here are the steps again to write and run an applet using the appletviewer (less memory and time than a browser).

    3.5.1 Write the applet in a source text file with extension *.java, e.g., TempApplet.java. Include the import lines and an init() method (and probably some others too)..

    3.5.2 Compile the applets with javac TempApplet.java in order to produce TempApplet.class file. Place the bytecode file in the same directory as the HTML file you are about to create.

    3.5.3 Create an HTML document with the appropriate APPLET tags in it. 3.5.4 View the HTML document with the appletviewer: appletviewer

    TempApplet.html.

    3.6 Addition Example.

    1) // Fig. 3.12: AdditionApplet.java 2) // Adding two floating-point numbers 3) import java.awt.Graphics; // import class Graphics 4) import javax.swing.*; // import package javax.swing 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) "Enter first floating-point value" ); 20) 21) // read in second number from user 22) secondNumber = 23) JOptionPane.showInputDialog( 24) "Enter second floating-point value" ); 25) 26) // convert numbers from type String to type double 27) number1 = Double.parseDouble( firstNumber ); 28) number2 = Double.parseDouble( secondNumber ); 29) 30) // add the numbers 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) }

  • Lesson 3 CSS 161A

    ECC Niko ulevski 15

    3.7 Drawing in Applets. The applet window can not only contain GUI components (textfields, labels, etc.) but it can be used as a simple canvas for drawing and including GIF and JPEG images.

    3.7.1 To draw in an applet, define the method public void paint (Graphics g). The paint method is called after the init() and start() method and when the applet window needs to be refreshed.

    3.7.2 The Graphics object g, which is created by t he browser not by you, is used for drawing operations.

    3.7.3 The applet grid has the point (0,0) at the top left corner (unlike in math) and distances are measure in pixels (about 1/50th of an inch).

    3.7.4 Few of the methods that the Graphics object has are: 3.7.4.1 drawLine(x1,y1,x2,y2); 3.7.4.2 drawRectangle(x1,y1,x2,y2); 3.7.4.3 drawOval(x1,y1,x2,y2); 3.7.4.4 fillRectangle(x1,y1,x2,y2); 3.7.4.5 fillOval(x1,y1,x2,y2); 3.7.4.6 drawString(string, x, y); 3.7.4.7 drawImage(im, x, y, this);

    3.7.5 MouseMaze Example

    import java.awt.*; import java.applet.*; import java.awt.event.*;

    public class MouseMaze extends Applet { // Draw a maze // Author: Samuel N. Kamin, June 1, 1996

  • Lesson 3 CSS 161A

    ECC Niko ulevski 16

    public void paint (Graphics g) { int size = 50; g.drawLine(1*size,1*size,4*size,1*size); // top of maze g.drawLine(1*size,1*size,1*size,2*size); // left side g.drawLine(1*size,3*size,1*size,4*size); g.drawLine(1*size,4*size,5*size,4*size); // bottom g.drawLine(5*size,1*size,5*size,4*size); // right side g.drawLine(2*size,2*size,2*size,4*size); // various walls g.drawLine(3*size,2*size,3*size,3*size); // various walls g.drawLine(4*size,3*size,4*size,4*size); // various walls g.drawLine(4*size,2*size,5*size,2*size); // various walls Image mouse = getImage(getDocumentBase(), "images/mouse.gif"); g.drawImage(mouse, 5, (int)(2.5*size), this); }

    }

    3.7.6 RandomCircles Example.

    import java.awt.*; import java.applet.*; import java.awt.event.*;

    public class RandomCircles extends Applet implements ActionListener { // Draw some random circles. // Author: Elaine M. Baranowicz, October 29, 1996

    Button circleButton;

    public void init () { circleButton = new Button("Circle"); add(circleButton); circleButton.addActionListener(this); }

    public void paint (Graphics g) { int diameter, radius, x, y, size = 300;

    // Generate a random center for the circle. x = (int) (size * Math.random());

  • Lesson 3 CSS 161A

    ECC Niko ulevski 17

    y = (int) (size * Math.random());

    // now randomly reduce the diameter diameter = (int) (300 * Math.random()); radius = (int)(diameter/2);

    g.drawOval(x-radius, y-radius, diameter, diameter); }

    public void actionPerformed (ActionEvent event) { repaint(); }

    public void update (Graphics g) { paint(g); } }

    3.8 Components. Refer to section 3.3 for a graphical representation of the subclasses of the class Component. Here is again:

    3.8.1 Size. The method getSize() gives the size of the applets drawing area. It produces an object of type Dimension.

    import java.awt.*; import java.applet.*; import java.awt.event.*;

    public class SetsizeApplet extends Applet { // Draw a big X // Author: Samuel N. Kamin, June 1, l996

    public void init() { // ensure the size we want setSize(100,300); }

    public void paint (Graphics g) { Dimension s = getSize(); int x = s.width, y = s.height; g.drawLine(0, 0, x, y); g.drawLine(x, 0, 0, y); g.fillOval(x/2-10,y/2-10,20,20);

  • Lesson 3 CSS 161A

    ECC Niko ulevski 18

    } }

    3.9 Thinking About Objects. Object orientation is a natural way of thinking about the world and of writing computer programs. Let us start by introducing some of the key terminology of object orientation.

    3.9.1 Everywhere you look you see themobjects! Humans think in terms of objects. We have the marvelous ability of abstraction, which enables us to view screen images as objects such as people, planes, trees and mountains rather than as individual dots of color (called pixels for "picture elements").

    3.9.2 All these objects, however, do have some things in common. They all have attributes like size, shape, color, weight and the like. And they all exhibit behaviors; for example, a ball rolls, bounces, inflates and deflates; a baby cries, sleeps, crawls, walks and blinks; a car accelerates, brakes and turns; a towel absorbs water.

    3.9.3 Object-oriented programming (OOP) models real-world objects with software counterparts. . It takes advantage of class relationships where objects of a certain class, such as a class of vehicles, have the same characteristics.

    3.9.4 It takes advantage of inheritance relationships where newly created classes of objects inherit characteristics of existing classes, yet contain unique characteristics of their own.

    3.9.5 OOP also models communication between objects. Just as people send messages to one another (e.g., a sergeant commanding troops to stand at attention), objects also communicate via messages.

    3.9.6 OOP encapsulates data (attributes) and methods (behavior) into packages called objects; the data and methods of an object are intimately tied together. Objects have the property of information hiding.

    3.9.7 In Java, the unit of programming is the class from which objects are eventually instantiated (a fancy term for "created"). Java classes contain methods (the corresponding concept to functions in C).

    3.9.8 Java programmers concentrate on creating their own user-defined types called classes. Each class contains data as well as the set of methods (or functions) that manipulate the data. The data components of a class are called instance variables (or data members).

    3.9.9 The function components of a class are called methods (some object-oriented programming languages call them member functions).

    3.9.10 Just as an instance of a built-in (primitive) type such as int is called a variable, an instance of a user-defined type (i.e., a class) is called an object (or instance).