Download presentation
Presentation is loading. Please wait.
1
Java I
2
Introduction to Java Applets
Chapter 3 Introduction to Java Applets
3
Applets Execute in a Browser
• There is no main method in a Java Applet. • A Java Applet can only run in a browser. • An Applet is run only when an HTML page requests that it be executed. • In place of a browser, we use a utility called the appletviewer This is a “minimal browser”—it ignores all other HTML commands except the one used to run an Applet. White Space Characters
4
Applets Execute in a Browser
appletviewer syntax. • To execute an Applet, do the following: Compile your Java Applet using javac, as usual. C:\ javac Hello.java Create an HTML file and name it: Example.html These parameters refer to the width and height (in pixels) of the box your Applet will get when it is executed on a web page. <HTML> <APPLET CODE=“Hello.class” WIDTH=300 HEIGHT=40> </APPLET> </HTML> White Space Characters To run the Applet, you type the following: C:\ appletviewer Example.html
5
A Simple Applet Writing A “String” (A Sentence) using an Applet
• Because an Applet gets help from a browser, it contains much less code. • The most obvious omission is the main method. White Space Characters
6
A Simple Applet // A First Applet import javax.swing.JApplet; import java.awt.Graphics; White Space Characters • Every Java Applet must commence by importing the class JApplet. • This class does all the heavy lifting for us.
7
A Simple Applet // A First Applet import javax.swing.JApplet; import java.awt.Graphics; White Space Characters • We are also importing class Graphics from the awt (Abstract Windowing Tools) package so that we can draw the String on the Applet.
8
A Simple Applet // A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { } • All code in an Applet sits in the wrapper of a class. • Likewise, the class name starts with a Capital • The public keyword enables the browser to create an instance of this class—what we have to do by ourselves in an Application. White Space Characters
9
Superclass (base class) JApplet Subclass (derived class) WelcomeApplet
A Simple Applet w // A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { } This is Inheritance—a very special principle—and there are special terms to describe the relationship. Superclass (base class) JApplet Subclass (derived class) WelcomeApplet White Space Characters • Take special note of the “extends” keyword. • extends means that our WelcomeApplet is building on top of another class, JApplet ! • We’re taking everything it has, and adding to it !
10
A Simple Applet • Now we have added a method called paint.
// A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { public void paint( Graphics g ) } White Space Characters • Now we have added a method called paint. • Notice its Access Modifier is public, so this method can be called by any object outside of this class. • The return value is void.
11
A Simple Applet Don’t get nervous. When you created an integer
// A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { public void paint( Graphics g ) } Don’t get nervous. When you created an integer variable ( int x; char m; ) you were doing the same thing, “Creating a instance of a type.” “ Graphics g ” is creating an example or instance of Graphics class and naming that instance g. White Space Characters • Apparently, the paint method of JApplet expects to be passed an object of type Graphics. • We are instantiating (creating) a Graphics class object called g right there, inside the parenthesis of paint.
12
A Simple Applet // A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { public void paint( Graphics g ) g.drawString( “Welcome to Java!”, 25, 25 ); } • Finally, with this statement, we use the Graphics class object g, and call the method drawString that all Graphics class objects have. • drawString expects a String, plus two coordinates that say where to place the bottom-left corner of the text. White Space Characters
13
A Simple Applet • Class JApplet already has a method called paint.
// A First Applet import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeApplet extends JApplet { public void paint( Graphics g ) g.drawString( “Welcome to Java!”, 25, 25 ); } • Class JApplet already has a method called paint. Class JApplet’s paint method is empty. It does nothing. • Although we did inherit the do-nothing method paint from JApplet, ours will do something. • We are overriding the method paint that we inherited. White Space Characters
14
Applets Execute in a Browser
Overriding a method • This process is central to inheritance. • Although we received a perfectly good method from the Superclass, we decided to create our own version of it—with the exact same name. • Since we used the same name, our version of the method takes over or overrides the method. • We haven’t affected the original copy of the method—it still exists—we just improved upon it in our own special Subclass. White Space Characters
15
Applets Execute in a Browser
• You might have to resize the Applet. You set the dimensions of this box in your Example.html file. • Note: When you resize the Applet, you trigger the paint method to fire. White Space Characters
16
More About Applets • In an Application, the method main is guaranteed to be called by the operating system. • In an Applet, which has no main method, three other methods are guaranteed to be called by the operating system: init() start() paint() ( In that order ) White Space Characters
17
More About Applets init() start() paint()
• Since we did not override init()and start(), the default versions of these methods were executed. • What did they do? Nothing! • Only paint() did something because we overrode it and made it do something useful. • Finally, anytime you resize an Applet (meaning drag the bottom right corner to make it bigger or smaller), then the method paint() is automatically called again. White Space Characters
18
Thinking About Objects
• Attributes and Behaviors: All Objects have them. • An Object in the real world has: Attributes--its qualities, and its Behaviors--what it does. Object: A balloon Attributes: Color: red Diameter: 2 inches Behaviors: Rises Inflates Deflates Pops White Space Characters
19
Thinking About Objects
• Java is based on the unit of a class. A class is an object, it encapsulates the attributes and behaviors into one self-contained unit. • The attributes (internal data variables) and behaviors (methods that have an effect on those internal data variables) are combined into a unit called an object. Java encapsulates data (attributes) and methods (behavior) into a unit called an Object. White Space Characters
20
Thinking About Objects
• Some objects are Similar—Java Takes Advantage of the Similarities A bicycle inner tube is a specific type of balloon. It has a color and a width It inflates, deflates and pops. I cannot change the diameter of the balloon without using the method of inflating it. Alone, I can’t change the diameter attribute of the inner tube. I have to use the method of inflating or deflating the inner tube to change its diameter attribute. We say the width attribute is hidden. I can’t change it without using the method. White Space Characters
21
Thinking About Objects • An Employee is an Object
A Generic Employee has attributes: name address phone_number social_security_number A Generic Employee has a method: calculate_pay White Space Characters
22
Thinking About Objects • An Employee is an Object
An Hourly Employee is a specific kind of Employee. It has the same Attributes as the Generic Employee, plus other Attributes: hourly_pay_rate overtime_hours An Hourly Employee has the same method: calculate_pay but the calculation is different. It uses hourly_pay_rate and overtime_hours. White Space Characters
23
Thinking About Objects • An Employee is an Object
A Salaried Employee is specific kind of Employee. It has all the same Attributes as the Generic Employee, plus another Attribute: salary A Salaried Employee has the same method: calculate_pay but the calculation is different. It uses salary. White Space Characters
24
Thinking About Objects • An Employee is an Object
A Commission Employee is specific kind of Employee. It has all the same Attributes as the Generic Employee, plus other Attributes: base_pay commission_rate A Commission Employee has the same method: calculate_pay but the calculation is different. It uses base_pay and commission_rate. White Space Characters
25
Thinking About Objects • An Employee is an Object
A Piecework Employee is specific kind of Employee. It has all the same Attributes as the Generic Employee, plus another Attribute: pay_per_piece A Piecework Employee has the same method: calculate_pay but the calculation is different. It uses pay_per_piece. White Space Characters
26
Thinking About Objects Inheritance
•The Hourly Employee, Salaried Employee, Commission Employee and Piecework Employee all... Inherit the Attributes and Behaviors of the Generic Employee. They elaborate on the stuff they inherited. Any Superclass methods that are appropriate are NOT overridden. Although they inherit from Generic Employee, the base is not changed. White Space Characters
27
Draw A Line • The Graphics class that drew the String on our previous Applet has many methods at our disposal. • To the list of API classes we must know, we must now add Graphics and JApplet. White Space Characters
28
Draw A Line • This will put lines above and below the sentence.
// Display Text and Lines import javax.swing.JApplet; import java.awt.Graphics; public class WelcomeLines extends JApplet { public void paint( Graphics g ) g.drawLine( 15, 10, 210, 10 ); g.drawLine( 15, 30, 210, 30 ); g.drawString( “Welcome to Java!”, 25,25); } White Space Characters • This will put lines above and below the sentence. • The 4 arguments are the beginning and end points of the line.
29
Draw A Line • This is the output. White Space Characters
30
Applet Example: Addition
• This will produce the same result as we achieved with the Addition Application, only this time as an Applet. • The goal is to add two floating-point numbers. White Space Characters
31
Two Kinds of Java Variables:
// Add two floating point numbers import javax.swing.*; import java.awt.Graphics; public class AdditionApplet extends JApplet { double sum; // instance variable public void init() } public void paint( Graphics g ) Two Kinds of Java Variables: Instance variables: • Declared outside of any method • Automatically initialized • Visible in all methods of the class Local variables: • Declared inside a method • Not automatically initialized—a syntax error if you try to use them with out first putting a value in. • Vanish after the method returns to whatever called it. This asterisk allows you to import all the classes in a package. ( But only the classes at this directory, not any sub-directories. ) Also, from that wildcard package, the compiler will only bring in those classes that you actually used in the program. Notice, this variable sum is outside of any method. sum is an instance variable. Numeric instance variables are automatically initialized to zero, char instance variables are automatically initialized to spaces and boolean are automatically initialized to false. White Space Characters w
32
// Add two floating point numbers import javax.swing.*;
import java.awt.Graphics; public class AdditionApplet extends JApplet { double sum; // instance variable public void init() String firstNumber, secondNumber; // local variables double num1, num2; // local variables } public void paint( Graphics g ) White Space Characters
33
( There are Type Wrapper classes for all the primitive data types. )
// Add two floating point numbers import javax.swing.*; import java.awt.Graphics; public class AdditionApplet extends JApplet { double sum; // instance variable public void init() String firstNumber, secondNumber; double num1, num2; firstNumber = JOptionPane.showInputDialog(“First Num” ); secondNumber = JOptionPane.showInputDialog(“Second Num” ); num1 = Double.parseDouble( firstNumber ); num2 = Double.parseDouble( secondNumber ); sum = num1 + num2; } public void paint( Graphics g ) White Space Characters Since num1 and num2 are doubles, we use the “Type Wrapper” class that can convert a String into a double. ( There are Type Wrapper classes for all the primitive data types. ) w
34
// Add two floating point numbers
import javax.swing.*; import java.awt.Graphics; public class AdditionApplet extends JApplet { double sum; // instance variable public void init() String firstNumber, secondNumber; double num1, num2; firstNumber = JOptionPane.showInputDialog(“First Num” ); secondNumber = JOptionPane.showInputDialog(“Second Num” ); num1 = Double.parseDouble( firstNumber ); num2 = Double.parseDouble( secondNumber ); sum = num1 + num2; } public void paint( Graphics g ) g.drawRect( 15, 10, 270, 20 ); g.drawString( “The Sum is ” + sum, 25, 25 ); White Space Characters • In drawRect, the parameters are the coordinates for the top left-hand corner, the width and the height.
35
Applet Example: Addition Output
White Space Characters
36
Another Word on Variables
• Earlier, we discussed the so-called primitive variables. The are so named, because they are not objects. For short, these are called just variables. int num1; double sum; White Space Characters
37
Another Word on Variables
• There is another group—reference variables. These are objects. String firstNumber; String secondNumber; The identifiers for these reference variables only contain references—that is, the address where this reference variable can be found in memory. White Space Characters
38
A Reference is a pointer !
• int num1 = 132; [Integers always take 4 bytes.] A primitive can only store one piece of data. num1 A Reference is a pointer ! firstNumber {This is the actual place in memory where the String Object stores everything it needs to accomplish its task as a String Object. Inevitably, it would be a lot more than a simple primitive... White Space Characters • String firstNumber = JOptionPane.showMessageDialog firstNumber is a reference (pointer) to the real Object. An object can store many kinds of data.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.