• No results found

Java Applets. CSE219, Computer Science III Stony Brook University

N/A
N/A
Protected

Academic year: 2021

Share "Java Applets. CSE219, Computer Science III Stony Brook University"

Copied!
48
0
0

Loading.... (view fulltext now)

Full text

(1)

CSE219, Computer Science III

Stony Brook University

http://www.cs.stonybrook.edu/~cse219

(2)

Java Applets

When you browse the Web, you frequently see the graphical

user interface and animation developed using Java.

These programs are called Java applets.

Suppose you want to develop a Java applet for the Sudoku game.

(3)

How to convert GUI applications

into applets?

The

<applet>

HTML Tag:

<applet

code=Classfilename.class

width=applet_viewing_width_in_pixels

height=applet_viewing_height_in_pixels

[archive=archivefile]

[codebase=applet_url]

[vspace=vertical_margin]

[hspace=horizontal_margin]

[align=applet_alignment]

[alt=alternative_text]

>

<param name=param_name1

value=param_value1>

</applet>

(4)

First Simple Applet

<html>

<head>

<title>Java Applet Demo</title>

</head>

<body>

<applet

code = "DisplayLabel.class"

width = 350

(5)

First Simple Applet

import

javax.swing.*;

public class

DisplayLabel

extends

JFrame {

public

DisplayLabel() {

add(

new

JLabel(

"Great!"

, JLabel.CENTER));

}

public static void

main(String[] args) {

JFrame frame =

new

DisplayLabel();

frame.setTitle(

"DisplayLabel"

);

frame.setSize(

200

,

100

);

frame.setLocationRelativeTo(

null

);

frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

frame.setVisible(

true

);

}

}

import

javax.swing.*;

public class

DisplayLabel

extends

JFrame {

public

DisplayLabel() {

add(

new

JLabel(

"Great!"

, JLabel.CENTER));

}

public static void

main(String[] args) {

JFrame frame =

new

DisplayLabel();

frame.setTitle(

"DisplayLabel"

);

frame.setSize(

200

,

100

);

frame.setLocationRelativeTo(

null

);

frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

frame.setVisible(

true

);

}

}

JApplet

(6)

Applications vs. Applets

Similarities

Since JFrame and JApplet both are subclasses of the Container

class, all the user interface components, layout managers, and

event-handling features are the same for both classes.

Differences

Applications are invoked from the static main method by the

Java interpreter, and applets are run by the Web browser. The

Web browser creates an instance of the applet using the applet’s

no-arg constructor and controls and executes the applet

(7)

Security Restrictions on Applets

Applets are not allowed to read from, or write to, the file

system of the computer viewing the applets.

Applets are not allowed to run any programs on the

browser’s computer.

Applets are not allowed to establish connections between the

user’s computer and another computer except with the

server where the applets are stored.

(8)

Conversions Between Applications

and Applets

Conversions between applications and

applets are simple and easy.

You can always convert an applet into an

application.

You can convert an application to an applet

(9)

Enabling Applets to Run as Applications

import javax.swing.*;

public class DisplayLabel extends JApplet {

public DisplayLabel() {

add(new JLabel("Great!", JLabel.CENTER));

}

public static void main(String[] args) {

// Create a frame

JFrame frame = new JFrame("Applet is in the frame");

// Create an instance of the applet

DisplayLabel applet = new DisplayLabel();

// Add the applet to the frame

frame.add(applet);

// Display the frame

frame.setSize(300, 100);

frame.setLocationRelativeTo(null); // Center the frame

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

(10)

The

Applet

Class

When the applet is loaded, the Web browser creates an

instance of the applet by invoking the applet’s no-arg

constructor.

The browser uses the init, start, stop, and destroy methods to

control the applet.

By default, these methods do nothing.

To perform specific functions, they need to be modified in the

(11)

Writing Applets

Always extends the

JApplet

class, which is a subclass of

Applet

for Swing components.

Override

init()

,

start()

,

stop()

, and

destroy()

if necessary.

By default, these methods are empty.

Add your own methods and data if necessary.

Embed the Applets in an HTML page.

(12)

Browser Calling Applet Methods

Loaded

Initialized

Browser

invokes init()

Destroyed

Created

Browser creates

the applet

JVM loads the

applet class

Started

Browser

invokes start()

Stopped

Browser

invokes start()

Browser invokes

destroyed()

Browser

invokes stop()

(13)

The

init()

Method

Invoked when the applet is first loaded and again if the applet

is reloaded.

A subclass of

Applet

should override this method if the

subclass has an initialization to perform.

The functions usually implemented in this method include

creating new threads, loading images, setting up user-interface

components, and getting string parameter values from the

(14)

The

start()

Method

Invoked after the

init()

method is executed; also called

whenever the applet becomes active again after a period of

inactivity (for example, when the user returns to the page

containing the applet after surfing other Web pages).

A subclass of

Applet

overrides this method if it has any

operation that needs to be performed whenever the Web

page containing the applet is visited.

An applet with animation, for example, might use the start

(15)

The

stop()

Method

The opposite of the

start()

method, which is called when

the user moves back to the page containing the applet; the

stop()

method is invoked when the user moves off the

page.

A subclass of

Applet

overrides this method if it has any

operation that needs to be performed each time the Web

page containing the applet is no longer visible.

When the user leaves the page, any threads the applet has

started but not completed will continue to run.

You should override the stop method to suspend the running

threads so that the applet does not take up system resources

when it is inactive.

(16)

The

destroy()

Method

Invoked when the browser exits normally to inform the

applet that it is no longer needed and that it should release

any resources it has allocated.

A subclass of

Applet

overrides this method if it has any

operation that needs to be performed before it is destroyed.

Usually, you won't need to override this method unless you

wish to release specific resources, such as threads that the applet

created.

(17)

Passing Parameters to Applets

<applet

code = "DisplayMessage.class"

width = 200

height = 50>

<param name=MESSAGE value="Welcome to Java">

<param name=X value=20>

<param name=Y value=20>

alt="You must have a Java-enabled browser to view the applet"

</applet>

Display a message at a specified location: the

message and the location (x, y) are obtained from

the HTML source.

(18)

Passing Parameters to Applets

import javax.swing.*;

public class DisplayMessage extends JApplet {

/** Initialize the applet */

public void init() {

// Get parameter values from the HTML file

String message = getParameter("MESSAGE");

int x = Integer.parseInt(getParameter("X"));

int y = Integer.parseInt(getParameter("Y"));

// Create a message panel

MessagePanel messagePanel = new MessagePanel(message)

messagePanel.setXCoordinate(x);

(19)

import java.awt.FontMetrics;

import java.awt.Dimension;

import java.awt.Graphics;

import javax.swing.JPanel;

public class MessagePanel extends JPanel {

/** The message to be displayed */

private String message = "Welcome to Java";

/** The x coordinate where the message is displayed */

private int xCoordinate = 20;

/** The y coordinate where the message is displayed */

private int yCoordinate = 20;

/** Indicate whether the message is displayed in the center */

private boolean centered;

/** The interval for moving the message horizontally

* and vertically */

private int interval = 10;

/** Construct with default properties */

public MessagePanel() {

(20)

/** Construct a message panel with a specified message */

public MessagePanel(String message) {

this.message = message;

}

/** Return message */

public String getMessage() {

return message;

}

/** Set a new message */

public void setMessage(String message) {

this.message = message;

repaint();

}

/** Return xCoordinator */

public int getXCoordinate() {

(21)

/** Return yCoordinator */

public int getYCoordinate() {

return yCoordinate;

}

/** Set a new yCoordinator */

public void setYCoordinate(int y) {

this.yCoordinate = y;

repaint();

}

/** Return centered */

public boolean isCentered() {

return centered;

}

/** Set a new centered */

public void setCentered(boolean centered) {

this.centered = centered;

repaint();

}

/** Return interval */

(22)

/** Set a new interval */

public void setInterval(int interval) {

this.interval = interval;

repaint();

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

if (centered) {

// Get font metrics for the current font

FontMetrics fm = g.getFontMetrics();

// Find the center location to display

int stringWidth = fm.stringWidth(message);

int stringAscent = fm.getAscent();

// Get the position of the leftmost character in the baseline

xCoordinate = getWidth() / 2 - stringWidth / 2;

(23)

/** Move the message left */

public void moveLeft() {

xCoordinate -= interval;

repaint();

}

/** Move the message right */

public void moveRight() {

xCoordinate += interval;

repaint();

}

/** Move the message up */

public void moveUp() {

yCoordinate -= interval;

repaint();

}

/** Move the message down */

public void moveDown() {

yCoordinate += interval;

repaint();

}

/** Override get method for preferredSize */

public Dimension getPreferredSize() {

(24)

Case Study: Bouncing Ball

An applet that displays a ball bouncing in a panel

We use two buttons to suspend and resume the movement and

(25)

Case Study: Bouncing Ball

BounceBallApplet

+BounceBallApplet()

+main(args: String[]): void

JApplet

BallControl

-ball: Ball

-jsbDelay: JScrollBar

-jbtResume: JButton

-jbtSuspend: JButton

+BallControl()

JPanel

Ball

-x: int

-y: int

-dx: int

-dy: int

-radius: int

-delay: int

-timer: Timer

+Ball()

+suspend(): void

+resume(): void

+setDelay(delay: int): void

JPanel

1 1

(26)

import javax.swing.Timer;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class Ball extends JPanel {

private int delay = 10;

// Create a timer with delay 1000 ms

private Timer timer = new Timer(delay, new TimerListener());

private int x = 0; private int y = 0; // Current ball position

private int radius = 5; // Ball radius

private int dx = 2; // Increment on ball's x-coordinate

private int dy = 2; // Increment on ball's y-coordinate

public Ball() {

timer.start();

}

(27)

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(Color.red);

// Check boundaries

if (x < 0 || x > getWidth())

dx *= -1;

if (y < 0 || y > getHeight())

dy *= -1;

// Adjust ball position

x += dx;

y += dy;

g.fillOval(x - radius, y - radius, radius * 2, radius * 2);

}

public void suspend() {

timer.stop(); // Suspend timer

}

public void resume() {

timer.start(); // Resume timer

}

public void setDelay(int delay) {

this.delay = delay;

(28)

import javax.swing.*; import java.awt.event.*; import java.awt.*;

public class BallControl extends JPanel { private Ball ball = new Ball();

private JButton jbtSuspend = new JButton("Suspend"); private JButton jbtResume = new JButton("Resume"); private JScrollBar jsbDelay = new JScrollBar(); public BallControl() {

// Group buttons in a panel JPanel panel = new JPanel(); panel.add(jbtSuspend);

panel.add(jbtResume);

// Add ball and buttons to the panel

ball.setBorder(new javax.swing.border.LineBorder(Color.red)); jsbDelay.setOrientation(JScrollBar.HORIZONTAL); ball.setDelay(jsbDelay.getMaximum()); setLayout(new BorderLayout()); add(jsbDelay, BorderLayout.NORTH); add(ball, BorderLayout.CENTER); add(panel, BorderLayout.SOUTH); // Register listeners jbtSuspend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {

ball.suspend(); }

(29)

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import javax.swing.*;

public class BounceBallApplet extends JApplet {

public BounceBallApplet() {

getContentPane().add(new BallControl());

}

public static void main(String[] args) {

BounceBallApplet applet = new BounceBallApplet();

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setTitle("BounceBallApplet");

frame.getContentPane().add(applet, BorderLayout.CENTER);

frame.setSize(400, 320);

frame.setVisible(true);

}

}

<html>

<head>

<title>Java Applet Demo</title>

</head>

<body>

<applet

code = "BounceBallApplet.class"

width = 350

height = 200>

</applet>

(30)

Case Study: TicTacToe

Cell

JPanel

(31)

Case Study: TicTacToe

1

9

TicTacToe

-whoseTurn: char

-cell: Cell[][]

-jlblStatus: JLabel

+TicTacToe()

+isFull(): boolean

+isWon(token: char): boolean

JApplet

Cell

Indicates which player has the turn, initially 'X'.

A 3 by 3, two dimensional array for cells.

A label to display game status.

Constructs the TicTacToe user interface.

Returns true if all cells are filled.

(32)

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

import javax.swing.border.LineBorder; public class TicTacToe extends JApplet {

// Indicate which player has a turn, initially it is the X player private char whoseTurn = 'X';

// Create and initialize cells

private Cell[][] cells = new Cell[3][3]; // Create and initialize a status label

private JLabel jlblStatus = new JLabel("X's turn to play"); /** Initialize UI */

public TicTacToe() {

// Panel p to hold cells

JPanel p = new JPanel(new GridLayout(3, 3, 0, 0)); for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

p.add(cells[i][j] = new Cell());

// Set line borders on the cells panel and the status label p.setBorder(new LineBorder(Color.red, 1));

jlblStatus.setBorder(new LineBorder(Color.yellow, 1)); // Place the panel and the label to the applet

add(p, BorderLayout.CENTER);

(33)

/** Determine if the player with the specified token wins */ public boolean isWon(char token) {

for (int i = 0; i < 3; i++)

if ((cells[i][0].getToken() == token) && (cells[i][1].getToken() == token) && (cells[i][2].getToken() == token)) { return true;

}

for (int j = 0; j < 3; j++)

if ((cells[0][j].getToken() == token) && (cells[1][j].getToken() == token) && (cells[2][j].getToken() == token)) { return true;

}

if ((cells[0][0].getToken() == token) && (cells[1][1].getToken() == token) && (cells[2][2].getToken() == token)) { return true;

}

if ((cells[0][2].getToken() == token) && (cells[1][1].getToken() == token) && (cells[2][0].getToken() == token)) { return true;

}

return false; }

// An inner class for a cell

public class Cell extends JPanel { // Token used for this cell private char token = ' '; public Cell() {

(34)

/** Return token */ public char getToken() {

return token; }

/** Set a new token */

public void setToken(char c) { token = c;

repaint(); }

@Override /** Paint the cell */

protected void paintComponent(Graphics g) { super.paintComponent(g);

if (token == 'X') {

g.drawLine(10, 10, getWidth() - 10, getHeight() - 10); g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10); }

else if (token == 'O') {

g.drawOval(10, 10, getWidth() - 20, getHeight() - 20); }

}

private class MyMouseListener extends MouseAdapter { @Override /** Handle mouse click on a cell */ public void mouseClicked(MouseEvent e) {

// If cell is empty and game is not over if (token == ' ' && whoseTurn != ' ') {

(35)

}

else {

// Change the turn

whoseTurn = (whoseTurn == 'X') ? 'O' : 'X'; // Display whose turn

jlblStatus.setText(whoseTurn + "'s turn"); } } } } }

/** This main method enables the applet to run as an application */ public static void main(String[] args) {

// Create a frame

JFrame frame = new JFrame("TicTacToe"); // Create an instance of the applet TicTacToe applet = new TicTacToe(); // Add the applet instance to the frame frame.add(applet, BorderLayout.CENTER); // Display the frame

frame.setSize(300, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);

} }

(36)

}

else {

// Change the turn

whoseTurn = (whoseTurn == 'X') ? 'O' : 'X'; // Display whose turn

jlblStatus.setText(whoseTurn + "'s turn"); } } } } }

/** This main method enables the applet to run as an application */ public static void main(String[] args) {

// Create a frame

JFrame frame = new JFrame("TicTacToe"); // Create an instance of the applet TicTacToe applet = new TicTacToe(); // Add the applet instance to the frame frame.add(applet, BorderLayout.CENTER); // Display the frame

frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

<html>

<head>

<title>Java Applet Demo</title>

</head>

(37)

Locating Resources from Applets

Due to security restrictions, applets cannot access local files.

How can an applet load resource files for image and audio?

Creating ImageIcon Using Absolute File Names

ImageIcon imageIcon = new

ImageIcon("c:\\book\\image\\us.gif");

jlbl.setIcon(imageIcon);

This approach suffers a problem. The file location is fixed since

it uses the absolute file path on Window. Thus, the program

cannot run on other platforms and cannot run as applet.

(38)

Locating Resources from Applets

Creating ImageIcon Using Relative File Names

Assume that image/us.gif is under the class directory, you can

circumvent this problem by using a relative path as follows:

ImageIcon imageIcon = new

ImageIcon("image/us.gif");

jlbl.setIcon(imageIcon);

This works fine with Java applications on all platforms, but

does not work with Java applets because applets cannot

(39)

Locating Resource Using the URL Class

The java.net.URL class can be used to identify files (image,

audio, text, etc.) on the Internet. In general, a URL

(Uniform Resource Locator) is a pointer to a “resource” on

the World Wide Web on a local machine or a remote host. A

resource can be something as simple as a file or a directory.

Directory

An applet or

application

A resource file

.

.

.

Class metaObject =

this

.getClass();

URL url = metaObject.getResource(resourceFilename);

.

.

.

(40)

Creating a URL from a Class Reference

A URL for a file can also be accessed from a class in a way

that is independent of the location of the file, as long as the

resource file is located in the class directory.

C:\book

An applet or

application

image

.

.

.

Class metaObject =

this

.getClass();

URL url = metaObject.getResource(

"image/us.gif"

);

.

(41)

Creating AudioClip from an Audio File

To play an audio file in an applet, first create an audio clip object for the audio

file. The audio clip is created once and can be played repeatedly without

reloading the file. To create an audio clip, use the static method

newAudioClip() in the java.applet.Applet class:

AudioClip audioClip = Applet.newAudioClip(url);

Audio was originally used with Java applets. For this reason, the AudioClip

interface is in the java.applet package.

The following statements, for example, create an AudioClip for the beep.au

audio file in the same directory with the class you are running.

Class class = this.getClass();

URL url = class.getResource("beep.au");

(42)

Playing Audio

To manipulate a sound for an audio clip, use the play(), loop(), and stop() methods in

java.applet.AudioClip.

«interface»

java.applet.AudioClip

+play()

+loop()

+stop()

Starts playing this audio clip. Each time this method

is called, the clip is restarted from the beginning.

Plays the clip repeatedly.

(43)

Packaging and Deploying Java Projects

What is JAR?

Java archive file can be used to group all the project files in a compressed file

for deployment.

The Java archive file format (JAR) is based on the popular ZIP file format.

This single file can be deployed on an end-user’s machine as an application. It

also can be downloaded to a browser in a single HTTP transaction, rather

than opening a new connection for each piece. This greatly simplifies

application deployment and improves the speed with which an applet can be

loaded onto a web page and begin functioning.

(44)

Creating JAR

You can use the JDK

jar

command to create an archive file. The

following command creates an archive file named TicTacToe.jar for

classes TicTacToe.class and TicTacToe$Cell.class.

jar -cf TicTacToe.jar TicTacToe.class TicTacToe$Cell.class

The

-c

option is for creating a new archive file, and the

-f

option

specifies the archive file’s name.

(45)

Viewing the Contents of a JAR File

(46)

Manifest File

A manifest file was created with the path name meta-inf\. The manifest is a

special file that contains information about the files packaged in a JAR file. For

instance, the manifest file in TicTacToe.jar contains the following information:

Manifest-Version: 1.0

Name: TicTacToe.class

Java-Bean: True

Name: TioTacToe$Cell.class

Java-Bean: True

(47)

Running Archived Projects Standalone

The manifest file must have an entry to contain the main class. For example,

to run TicTacToe, you need to insert the following two lines in the manifest

file:

Main-Class: TicTacToe

Sealed: true

Run the .jar file using the java command from the directory that contains

TicTacToe.jar,

(48)

Running Archived Projects As Applet

To run TicTacToe as an applet, modify the <APPLET> tag in the

HTML file to include an ARCHIVE attribute. The ARCHIVE

attribute specifies the archive file in which the applet is contained.

For example, the HTML file for running TicTacToe can be

modified as shown below:

<APPLET

CODE = "TicTacToe.class"

ARCHIVE = "TicTacToe.jar"

WIDTH = 400

HEIGHT = 300

HSPACE = 0

References

Related documents

Determine which encryption cipher is used for the database on the Android, BlackBerry and iPhone operating system in the first week of the project?. 2.3.2 How strong is

Privately- funded Schools determine their own curriculum and provide more options for Singapore students (4–6 years) Special Education Schools provide EITHER

There’s only one practical solution to high- rise fires in over 800 unprotected Chicago high- rises, as well as all the new multiple floor buildings going up … and that’s fire

Namely, generic elementary embeddings are used in order to characterize levels of supercompact- ness, almost huge cardinals and super almost huge cardinals through Neeman’s pure

Supporting partners; prototype + additional support during qualification ExxonMobil, Shell &amp; Statoil. Priority customers (first users) ExxonMobil, Shell

Based on this, this paper mainly studies the multirobot autonomous navigation problem in power stations of smart microgrids, and multimobile robots are used to complete the

There are significant limits on the maximum diameter that a borehole can be drilled in hard rock to depths of about 4 km, so that, to allow the maximum amount of waste to be

(2004) Comparison of MPEG-7 audio spectrum projection features and MFCC applied to speaker recognition, sound classification and audio segmentation, In : Proceedings of the