CSE219, Computer Science III
Stony Brook University
http://www.cs.stonybrook.edu/~cse219
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.
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>
First Simple Applet
<html>
<head>
<title>Java Applet Demo</title>
</head>
<body>
<applet
code = "DisplayLabel.class"
width = 350
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
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
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.
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
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);
}
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
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.
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()
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
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
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.
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.
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.
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);
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() {
/** 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() {
/** 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 */
/** 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;
/** 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() {
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
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
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();
}
@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;
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(); }
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>
Case Study: TicTacToe
Cell
JPanel
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.
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);
/** 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() {
/** 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 != ' ') {
}
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);
} }
}
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); } }