import java.awt.Graphics;
import java.awt.Font;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
/**
* Peter Norton's Guide to Programming Java
* The Java ScrollText Applet
* This applet is used to scroll a text banner across the screen
* The applet takes TEXT, WIDTH, and HEIGHT as parameters.
*/
public class ScrollText extends java.applet.Applet implements MouseListener, Runnable {
int h; // Height of applet in pixels
int w; // Width of applet in pixels
char separated[]; // Output string in array form
String s = null; // Input string containing display text
String hs = null; // Input string containing height
String ws = null; // Input string containing width
Thread ScrollThread = null; // Thread to control processing
int speed=35; // Length of delay in milliseconds
boolean threadSuspended = false;
int dist;
/* Setup width, height, and display text */
public void init() {
ws = getParameter ("width");
hs = getParameter ("height");
if (ws == null){ // Read width as input
w = 150; // If not found use default
} else {
w = Integer.parseInt(ws); // Convert input string to integer
}
if (hs == null){ // Read height as input
h = 50; // If not found use default
} else {
h = Integer.parseInt (hs); // Convert input string to integer
}
resize(w,h); // Set font based on height
setFont(new Font("TimesRoman",Font.BOLD,h - 2));
s = getParameter("text");// Read input text, if null use default
if (s == null) {
s = " The Java ScrollText Applet at work.";
}
separated = new char [s.length()];
s.getChars(0,s.length(),separated,0);
}
/* Start new thread to run applet */
public void start() {
if(ScrollThread == null)
{
ScrollThread = new Thread(this);
ScrollThread.start();
}
}
/* End thread containing applet */
public void stop() {
ScrollThread = null;
}
// While applet is running pause then scroll text
public void run() {
while (ScrollThread != null) {
try {Thread.sleep(speed);} catch (InterruptedException e){}
scroll();
}
ScrollThread = null;
}
// Scroll text by determining new location to draw text and redrawing
synchronized void scroll () {
dist--; // Move string to left
// If string has disappeared to the left, move back to right edge
if (dist + ((s.length()+1)*(h *5 / 11)) == 0){
dist=w;
}
repaint();
}
// Redraw string at given location
public void paint(Graphics g) {
g.drawChars(separated, 0, s.length(), dist,4 *h / 5);
}
// Suspend thread when mouse is pushed, resume when pushed again
public void mousePressed(MouseEvent evt) {
if (threadSuspended) {
ScrollThread.resume();
}
else {
ScrollThread.suspend();
}
threadSuspended = !threadSuspended;
return true;
}
}