Download An Example

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming and Problem Solving
With Java
Applets
What is an Applet?
Applet Parameters
Graphics in Applets
Other Applet Methods
Copyright 1999, James M. Slack
Applets
Kinds of programs in Java
Applications: standalone programs
Applets: run inside a Web browser window
Browser downloads and executes Java applets
automatically
Java applets usually stored on Web server
JVM in browser executes the Java code
Advantage of applets
Only deploy once (on server)
In 2-tier client/server, each client has copy of client code
(must deploy new code to all clients)
Applets have sparked revolution in computing
Programming and Problem Solving With Java
2
What’s an Applet?
Program that runs inside a Web browser
Browser contains JVM for executing Java programs
The browser has the main() method -- it calls methods in
the applet
What about security?
Can a downloaded Java program wreck your computer?
Not easily -- downloaded Java program is restricted in
what it can do
Applet can read or write files on server
Allows applet to save information to server’s database
(for example)
Programming and Problem Solving With Java
3
What’s an Applet?
Example applet
Must extend the Applet class
// A simple Java applet that displays the
// word "Hello"
import java.applet.*;
import java.awt.*;
public class Hello extends Applet
{
public void init()
{
this.add(new Label("Hello!"));
}
}
Compile the same way as usual (javac Hello.java)
Programming and Problem Solving With Java
4
What’s an Applet?
Can’t run applet with java Hello
Must create a Web page to run it
Should be in same directory as Java applet (Hello.class)
<!-- An example HTML document that starts a Java applet -->
<HTML>
<HEAD>
<TITLE>HTML Page for Testing Applets</TITLE>
</HEAD>
<BODY>
<H1>HTML Page for Testing Applets</H1>
This is some ordinary HTML text, which is part of an ordinary
HTML document.
<P>
We can include Java applets to spice up the document. For
example, here is my "Hello" applet:
<P>
<APPLET CODE=Hello WIDTH=200 HEIGHT=100>
</APPLET>
<P>
That's the end of the document!
</BODY>
</HTML>
Programming and Problem Solving With Java
5
What’s an Applet?
Programming and Problem Solving With Java
6
HTML
Skeleton HTML document for applets
<!-- A skeleton HTML document -->
<HTML>
<HEAD>
<TITLE>Title for browser window</TITLE>
</HEAD>
<BODY>
... Text and HTML formatting tags here ...
</BODY>
</HTML>
HTML
Formatting tags (anything between <..> )
Beginning tag: <SOMETHING>
Ending tag: </SOMETHING>
<HEAD> ... </HEAD> is for document info
<BODY> ... </BODY> is what browser displays
Programming and Problem Solving With Java
7
HTML
Common HTML tags
Tag
Description
<APPLET> ... </APPLET>
Java applet
<TITLE> ... </TITLE>
Title for the title bar of the browser window
<H1> ... </H1>, <H2> ... <H2>,
etc.
Headings
<P>
New paragraph
<HR>
Horizontal rule
<BR>
Break line
<!-- ... -->
Comment
<I> ... </I>
Italics
<B> ... </B>
Bold
Programming and Problem Solving With Java
8
HTML
APPLET tag
Example
<APPLET CODE=Hello WIDTH=200 HEIGHT=100>
</APPLET>
Minimum attributes
CODE: tells browser name of the Java class file (should
be in same directory as HTML document)
WIDTH: width of the applet in pixels
HEIGHT: height of the applet in pixels
Programming and Problem Solving With Java
9
Applet Viewer
Can be tedious to load applet into HTML document
in full browser
Applet viewer
Small program (much smaller than browser)
Reads text file, looks for APPLET tag
Text file can be HTML, but
doesn’t need to be (just
needs APPLET tag)
Will start any applets (marked
with APPLET tags) in the
text file
Example
appletviewer Applets.html
Programming and Problem Solving With Java
10
Applet Viewer (A Little Trick...)
Applet viewer reads any text file
Therefore, put APPLET tag in applet! (documentation!!)
Needs to be a Java comment
// A simple Java applet that displays the word "Hello"
/* Sample tag:
<APPLET CODE=Hello WIDTH=200 HEIGHT=100>
</APPLET>
*/
import java.applet.*;
import java.awt.*;
public class Hello extends Applet
{
public void init()
{
this.add(new Label("Hello!"));
}
}
To compile and run
javac Hello.java
appletviewer Hello.java
Programming and Problem Solving With Java
11
LoanPayment Applet
1  (1  interestRate)  months 
payment  amount  

interestRa
te


Programming and Problem Solving With Java
12
LoanPayment Applet
Very similar to writing GUI application
Define buttons, labels, and text fields
Choose and initialize the layout manager
Connect the bought in to a listener object
actionPerformed() method for handling events
Differences
Import java.applet.*
Extend the Applet class, not Frame
Initialization code goes in init(), not constructor
Don't call parent class constructor
Don't set the size of the applet--browser gets size from
APPLET tag in HTML document
No main() -- browser starts applet
Programming and Problem Solving With Java
13
LoanPayment Applet
// An applet that computes the payment on a loan,
// based on the amount of the loan, the interest rate, and the
// number of months
/* Sample tag:
<APPLET CODE=LoanPayment WIDTH=300 HEIGHT=100>
</APPLET>
*/
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.text.*;
public class LoanPayment extends Applet implements ActionListener
{
// Interface variables
TextField amountTextField = new TextField(15);
TextField rateTextField = new TextField(15);
TextField monthsTextField = new TextField(15);
Button computePaymentButton = new Button("Compute payment");
Label resultLabel = new Label();
Programming and Problem Solving With Java
14
LoanPayment Applet
public void init()
{
// Choose the layout manager and initialize it
this.setLayout(new GridLayout(4, 2));
// Put components on the applet
this.add(new Label("Loan amount: "));
this.add(this.amountTextField);
this.add(new Label("Annual interest rate: "));
this.add(this.rateTextField);
this.add(new Label("Months: "));
this.add(this.monthsTextField);
this.add(this.computePaymentButton);
this.add(this.resultLabel);
}
// Register the button with the listener object
this.computePaymentButton.addActionListener(this);
Programming and Problem Solving With Java
15
LoanPayment Applet
// actionPerformed: Compute the loan payment based on the amount
//
of the loan, the annual interest rate, and the
//
months of the loan
public void actionPerformed(ActionEvent event)
{
NumberFormat formatter = NumberFormat.getInstance();
try
{
double loanAmount
= formatter.parse(amountTextField.getText()).doubleValue();
double interestRate
= formatter.parse(rateTextField.getText()).doubleValue();
double months
= formatter.parse(monthsTextField.getText()).doubleValue();
// Convert annual interest rate to monthly
interestRate = interestRate / 12;
double payment
= loanAmount
/ ((1 - Math.pow(1 + interestRate, -months)) / interestRate);
}
}
this.resultLabel.setText("Payment is " + payment);
}
catch (ParseException e)
{
this.resultLabel.setText("Error in values");
}
Programming and Problem Solving With Java
16
Applet Parameters
Can pass values from HTML document to applet
Applet parameter
Text value in HTML
Applet can read value
Can make applet do different things in different contexts
Reduces the number of applets we need to write
Example
HTML
<APPLET CODE=AskQuestion WIDTH=300 HEIGHT=100>
<PARAM NAME=naturalLanguage VALUE=English>
</APPLET>
In applet
String natLanguage = getParameter("naturalLanguage");
Applet can test the value (String.equals()) and act on it
Programming and Problem Solving With Java
17
Applet Parameters
Can pass any number of parameters from HTML to
applet
Example
HTML
<APPLET CODE=TestApplet WIDTH=300 HEIGHT=100>
<PARAM NAME=naturalLanguage VALUE=English>
<PARAM NAME=userName VALUE=smith>
<PARAM NAME=password VALUE=wxyz>
</APPLET>
In applet
String natLanguage = getParameter("naturalLanguage");
String userName = getParameter("userName");
String password = getParameter("password");
Programming and Problem Solving With Java
18
Applet Parameters (LoanPayment)
Updated LoanPayment program uses applet
parameter to tell whether interest rate is monthly or
annual
//
//
//
//
//
//
An applet that computes the payment on a loan,
based on the amount of the loan, the interest rate, and the
number of months Takes one parameter from the browser:
monthlyRate. If true, the interest rate is per month; otherwise,
the interest rate is annual. (The differences between this
listing and Listing F.5 are highlighted.)
/* Sample tag:
<APPLET CODE=LoanPayment WIDTH=300 HEIGHT=100>
<PARAM NAME=monthlyRate VALUE=false>
</APPLET>
*/
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.text.*;
Programming and Problem Solving With Java
19
Applet Parameters (LoanPayment)
public class LoanPayment extends Applet implements ActionListener
{
// Interface variables
TextField amountTextField = new TextField(15);
TextField rateTextField = new TextField(15);
TextField monthsTextField = new TextField(15);
Button computePaymentButton = new Button("Compute payment");
Label resultLabel = new Label();
boolean monthlyRate;
public void init()
{
// Get the monthlyRate parameter from the browser
this.monthlyRate = getParameter("monthlyRate").equals("true");
// Choose the layout manager and initialize it
this.setLayout(new GridLayout(4, 2));
// Put components on the applet
this.add(new Label("Loan amount: "));
this.add(this.amountTextField);
Programming and Problem Solving With Java
20
Applet Parameters (LoanPayment)
if (this.monthlyRate)
{
this.add(new Label("Monthly interest rate: "));
}
else
{
this.add(new Label("Annual interest rate: "));
}
this.add(this.rateTextField);
this.add(new Label("Months: "));
this.add(this.monthsTextField);
this.add(this.computePaymentButton);
this.add(this.resultLabel);
}
// Register the button with the listener object
this.computePaymentButton.addActionListener(this);
Programming and Problem Solving With Java
21
Applet Parameters (LoanPayment)
// actionPerformed: Compute the loan payment based on the amount
//
of the loan, the annual interest rate, and the
//
months of the loan
public void actionPerformed(ActionEvent event)
{
NumberFormat formatter = NumberFormat.getInstance();
try
{
double loanAmount
= formatter.parse(amountTextField.getText()).doubleValue();
double interestRate
= formatter.parse(rateTextField.getText()).doubleValue();
double months
= formatter.parse(monthsTextField.getText()).doubleValue();
// Convert annual interest rate to monthly (if applicable)
if (!this.monthlyRate)
{
interestRate = interestRate / 12;
}
Programming and Problem Solving With Java
22
Applet Parameters (LoanPayment)
double payment
= loanAmount
/ ((1 - Math.pow(1 + interestRate, -months)) / interestRate);
this.resultLabel.setText("Payment is " + payment);
}
}
}
catch (ParseException e)
{
this.resultLabel.setText("Error in values");
}
Programming and Problem Solving With Java
23
Applet Parameters (LoanPayment)
HTML document for LoanPayment
<!-- This HTML document shows how to use an applet
parameter to make the same applet behave differently, depending
on the parameter value. The document loads the LoanPayment
applet (Listing F.6) with the monthlyRate parameter set to
"false", then loads the LoanPayment applet with the monthlyRate
parameter set to "true". -->
<HTML>
<HEAD>
<TITLE>Loan Payment Computation</TITLE>
</HEAD>
<BODY>
<H1>Loan Payment Computation</H1>
This page contains two copies of one applet that
computes the payment on a loan. The applet bases
this on the amount of the loan, the interest rate,
and the number of months of the loan.
<P>
Use the following copy of the applet if you want to
enter an <B>annual</B> interest rate.
<P>
Programming and Problem Solving With Java
24
Applet Parameters (LoanPayment)
<APPLET CODE=LoanPayment WIDTH=300 HEIGHT=100>
<PARAM NAME=monthlyRate VALUE=false>
</APPLET>
<P>
Use the following copy of the applet if you want to
enter a <B>monthly</B> interest rate.
<P>
<APPLET CODE=LoanPayment WIDTH=300 HEIGHT=100>
<PARAM NAME=monthlyRate VALUE=true>
</APPLET>
<P>
Thank you for trying the Loan Payment Computation Web page!
</BODY>
</HTML>
Programming and Problem Solving With Java
25
Applet Parameters (LoanPayment)
Programming and Problem Solving With Java
26
Graphics in Applets
Almost the same as writing graphics applications
Example
// Demonstration of the drawLine() method in an applet
/* Sample tag:
<APPLET CODE=DrawLine WIDTH=200 HEIGHT=200>
</APPLET>
*/
import java.applet.*;
import java.awt.*;
public class DrawLine extends Applet
{
// paint: Display a square with an X inside
public void paint(Graphics g)
{
g.drawLine(40, 40, 40, 160);
g.drawLine(40, 160, 160, 160);
g.drawLine(160, 160, 160, 40);
g.drawLine(160, 40, 40, 40);
g.drawLine(40, 40, 160, 160);
g.drawLine(40, 160, 160, 40);
}
Programming and Problem Solving With Java
27
Other Applet Methods
We’ve seen init(), paint(), repaint()
Use init() like a constructor -- set layout manager, put
components on window
Use paint() to draw
Use repaint() to tell system to use paint() again
Other methods
stop(): Called when user scrolls applet off screen. Use to
stop animation.
start(): Called when user scrolls applet back on screen.
Use to start animation.
destroy(): Called when user leaves browser page. Use to
clean up (close files, etc.)
Programming and Problem Solving With Java
28