CIS 121 March 20, 2000
Applets
There are a few methods which Applets inherit from the Component class
that are useful.
One of these methods is the paint method. The parameter to the paint
method is a Graphics object.
Another import method is the update method. By default, this method will
clear the entire drawing area and then call the paint method. The parameter
to the update method is a Graphics object.
The default behavior of the update() method is
g.setColor(getBackground());
g.fillRect(0,0,width,height);
g.setColor(getForeground());
paint(g);
A third import method is the repaint method. The repaint method has
no parameters. When the repaint method is called, the method update and,
therefore, paint, is called as soon as the calling environment (browser/appletviewer)
can call it.
We can override both the paint and update methods in our applet.
When we want to draw a figure on the screen, we create a Graphics object
associated with the drawing area. By default when we make calls to the
update and paint methods, the Graphics object associated with the current
object.
Let us look at a few examples of using the Graphics class, and the
methods available to us.
The Graphics Class
Recall that the Graphics Class is an abstract class, and, therefore,
cannot be instantiated with a constructor. It must be instantiated
through a call to the method getGraphics() in the Component class. Classes
which inherit from Component may call this method to instantiate a
Graphics object associated with them.
Let us examine some of the methods available when we instantiate a
Graphics object.
public abstract void clearRect(int x,int y,int width,int height)
clearRect will clear a rectangular section of the drawing area. The first
two parameters are the coordinates of the upper left-hand corner of the
section relative to the upper left-hand corner of the drawing area. The
second two parameters are the width and height of the section. The color
that is used is the current background color.
public abstract void drawLine(int xl,int yl,int x2,int y2)
This method draws a line in the drawing area. The first two parameters
are the coordinates of one end of the line. The second two parameters
are the coordinates of the other end of the line.
public abstract void drawRect(int x,int y,int width,int height)
public abstract void fillRect(int x,int y,int width,int height)
public abstract void drawOval(int x,int y,int width,int length)
public abstract void fillOval(int x,int y,int width,int height)
public abstract void drawPolygon(int xpoints[],int ypoints[],int points)
This method allows us to draw a polygon on the screen. We send to this
method three parameters. The first two are arrays of x and y values. The
third is the number of points in the polygon.
public abstract void fillPolygon(int xpoints[],int ypoints[],int points)
We may also draw a filled polygon.
public abstract void setColor(Color c)
When we draw text or Graphics on the screen we may specify a color.
public abstract void setFont(Font font)
When drawing text on the screen we may specify a font type to use.
We have seen that many times an applet needs to run in its own thread.
Here is an example of using multithreading to implement a simple
animation.
import java.awt.*;
import java.applet.*;
public class Example11 extends Applet implements Runnable {
int x = 50;
int y = 50;
Thread example;
public Example11() {
setLayout(null);
setBackground(Color.white);
}
public void init() {
if (example == null) {
example = new Thread(this);
example.start();
}
}
public void run() {
while (true) {
x++;
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
}
if (x==250)
x=50;
}
}
public void update(Graphics g) {
System.out.println("Hello");
g.setColor(getBackground());
g.clearRect(x-1,y,50,50);
g.setColor(getForeground());
paint(g);
}
public void paint(Graphics g) {
g.fillOval(x,y,50,50);
}
public void destroy() {
if (example != null) {
example.stop();
example = null;
}
}
}
Demonstration of Applet
So let us review some of the things we have seen about applets.
- In order to use applets, we must import the java.applet package.
- We always extend the Applet class.
- An apple cannot run by itself. It must be run in the context of
a browser or appletviewer.
- The first method executed when an applet is loaded is the constructor
if there is one.
- The next method executed is the init() method. The init() method is
executed one time when the applet is loaded.
- The next method executed is the start() method. The start() method is
executed each time the applet becomes visible.
- The stop() method is executed each time the applet becomes invisible, e.g.
when the browser or appletviewer window is minimized.
- The destroy() method is executed one time when the browser or appletviewer
is closed.
- Since an Applet is a Panel, we can break the applet up into smaller
Panels, and in each of those Panels we can place valid Components.
Let us also review the procedures we have discussed to accomplish the
various pieces of your assignment.
Partitioning the screen into an area in which components are placed
and an area in which figures are displayed.
- Set the Layout manager for the applet to null.
- Create the two Panel objects.
- Decide on the size and location of those Panel objects.
- Add the two Panel objects into the applet.
Creating buttons and having actions take place based on button
clicks.
- Create the Applet and implement the ActionListener interface.
- Create a Button object, button, and give it a label, buttonLabel.
- Tell the interpreter to listen for a user to click the button by
adding the line button.addActionListener(this);.
- Add the button into the appropriate Panel object.
- Since we are implementing the ActionListener interface, we must
implement the method public void actionPerformed(ActionEvent e);.
- Within the actionPerformed method, we may access the button that
caused the event to occur with either the method getSource() or the
method getActionCommand(). getSource() returns an object, and getActionCommand()
returns the string associated with the button. Recall that in order to
use getSource() we need to make the Button object an instance variable.
Creating textboxes in which information will be placed and from which
information will be retrieved.
- Create a TextField component or TextArea component.
- Remember that we need to make the component an instance variable if
we wish to access it in the methods we implement.
- Add the component into the appropriate field.
- We can place text into the component by using the setText() method.
- We can retrieve text from the component by using the getText() method.
- Since we are retrieving a string from the component, if we wish to
use it as a number we must convert it to a number. We can do this by
using the valueOf method in the appropriate object in java.lang, e.g.
Integer, Float, etc. After converting the string to the appropriate object
we then call the method which will convert the number in the object to
one of the primitive types. For example, to convert the text in TextField
to an int,
int value = (Integer.valueOf(myTextField.getText())).intValue();
Creating checkboxes and performing actions based on which box(es) are
checked.
- Create the Applet and implement the ItemListener interface.
- Create Checkbox objects, e.g. checkbox, and add them to the appropriate panel.
- Add item listeners to each checkbox component with the line
checkbox.addItemListener(this);.
- Since we are implementing the ItemListener interface, we must
implement the method public void itemStateChanged(ItemEvent e);.
- When a box is checked or unchecked, an ItemEvent is created,
and itemStateChanged is called.
- We use the method getStateChange() to determine whether a box was
checked or unchecked.
- There are several static int variables defined in the ItemEvent
class.
- Two of these static ints are SELECTED and DESELECTED.
- Once we have determined whether a box was checked or unchecked, we
use the method getItem() to get the string value associated with the
box that was checked or unchecked.
- We may use the method getState() to determine whether a box is checked
or unchecked. This method returns a boolean.
- We may use the method setState(boolean b) to check a box or uncheck it.
Drawing a figure on the screen for a random amount of time.
- In order to obtain a random number we use the method Random() in the
class Math in java.lang. Random() returns a double between 0 and 1. In order
to generate a random number between 0 and x, we multiply the return value by
x. To generate a random integer between 0 and x, we cast the result as
an int.
- We use the concept of threads in order to accomplish having the figure
on the screen for a random amount of time. We use the simple scheme of
draw, wait, and redraw.
Setting up a timer.
import java.awt.*;
import java.applet.*;
import java.util.*;
public class Exercise6 extends Applet {
TextField timeLeft;
Thread timer;
public class Timer implements Runnable {
int hours;
int minutes;
int seconds;
Calendar time;
int base;
boolean first=true;
int basehours;
int baseminutes;
int baseseconds;
public void run() {
timeLeft.setText(" ");
while (true) {
if (first) {
time = Calendar.getInstance();
basehours = time.get(Calendar.HOUR_OF_DAY);
baseminutes = time.get(Calendar.MINUTE);
baseseconds = time.get(Calendar.SECOND);
System.out.println(basehours + " " + baseminutes + " " + baseseconds);
base = basehours*60*60+baseminutes*60+baseseconds;
System.out.println(base);
first=false;
}
time = Calendar.getInstance();
hours = time.get(Calendar.HOUR_OF_DAY);
minutes = time.get(Calendar.MINUTE);
seconds = time.get(Calendar.SECOND);
int current = hours*60*60+minutes*60+seconds;
timeLeft.setText(String.valueOf(301-(current-base)));
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
System.exit(1);
}
}
}
}
public Exercise6() {
setLayout(new FlowLayout());
timeLeft = new TextField("300");
add(timeLeft);
}
public void init() {
if (timer == null) {
timer = new Thread(new Timer());
timer.start();
}
}
public void destroy() {
timer.stop();
}
}
Capturing a mouse click event and using the coordinates to aim an
imaginary gun.
- Create the Applet and implement the MouseListener interface.
- Tell the interpreter to listen for Mouse Events by adding the line
addMouseListener(this) to the appropriate Panel.
- Implement all the methods in the MouseListener interface, in particular
mousePressed.
- Use the getX() and getY() methods to get the coordinates of the mouse
click relative to the upper left-hand corner of the Panel.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Exercise7 extends Applet implements MouseListener {
Panel panel;
public Exercise7() {
setLayout(null);
panel = new Panel(null);
panel.setSize(500,300);
panel.setLocation(0,0);
panel.addMouseListener(this);
add(panel);
}
public void mousePressed(MouseEvent e) {
int x=0;
int y;
int x1 = e.getX();
int y1 = e.getY();
int xd=(250-x1)*(250-x1);
int yd=(300-y1)*(300-y1);
double diagonalDistance = Math.sqrt((250-x1)*(250-x1)+(300-y1)*(300-y1));
int verticalDistance = Math.abs(300-y1);
int horizontalDistance = Math.abs(250-x1);
int horizontalDirection = 250-x1;
int t = (int)(30*verticalDistance/diagonalDistance);
int s = (int)(30*horizontalDistance/diagonalDistance);
if (horizontalDirection<=0) {
x = 250+s;
} else if (horizontalDirection>0) {
x = 250-s;
}
y = 300-t;
Graphics g = panel.getGraphics();
g.drawLine(250,300,x,y);
}
public void mouseClicked(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
Demonstration of Applet
Detecting whether the figure was hit.
- Recall that in order for a figure to be hit, the mouse click must
be in the direction of the figure, and there must be enough time for the
bullet to get to the figure.
Handle any exceptions which might occur.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Exercise9 extends Applet implements ItemListener {
Checkbox on;
Checkbox off;
TextField myTextField;
public class MyException extends Exception {
String s;
public MyException(String s) {
this.s = s;
}
}
public Exercise9() {
setLayout(null);
Panel panel1 = new Panel(new FlowLayout());
Panel panel2 = new Panel(new FlowLayout());
myTextField = new TextField(100);
panel1.add(myTextField);
panel1.setSize(500,100);
panel1.setLocation(0,0);
on = new Checkbox("On");
off = new Checkbox("Off");
on.addItemListener(this);
off.addItemListener(this);
panel2.add(on);
panel2.add(off);
panel2.setSize(500,100);
panel2.setLocation(0,100);
add(panel1);
add(panel2);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
if (on.getState() && off.getState())
throw new MyException("You can't check both boxes at the same time.");
else if (on.getState() || off.getState())
myTextField.setText("");
} catch (MyException exc) {
myTextField.setText(exc.s);
on.setState(false);
off.setState(false);
}
}
}
}
Demonstration of Applet