/**************************************************/ /* Java Lab 1 i Programspråk */ /**************************************************/ /* Textsträng som fladdrar runt i appleten */ /**************************************************/ /* Christian Ohlsson di7chro@cse.kau.se */ /**************************************************/ import java.applet.*; import java.awt.*; import java.awt.image.*; public class HelloWorld extends Applet implements Runnable { Thread animationThread = null; int delay=100, xspeed, yspeed; int xsize, ysize, xOffset, yOffset, helloTextWidth, helloTextHeight; Image backBuffer; Graphics backGC; // Graphics Context String helloText; // Initialize the Applet public void init() { xsize=getSize().width; ysize=getSize().height; backBuffer = createImage(xsize, ysize); backGC = backBuffer.getGraphics(); // Get the text from the html page that the user wants to scroll helloText=getParameter("text"); String s=getParameter("speed"); xspeed=yspeed= Integer.parseInt(s); // Calculate the real size of the string using the font FontMetrics fontInfo=backGC.getFontMetrics(); helloTextWidth=fontInfo.stringWidth(helloText); helloTextHeight=fontInfo.getHeight(); xOffset=5; yOffset=5; yOffset=helloTextHeight; } // This method is called when the applet becomes visible public void start() { // Create a thread and start it if(animationThread == null) { animationThread = new Thread(this); animationThread.start(); } } // This method is called when the applet becomes invisible public void stop() { // Stop animation thread animationThread = null; } public void run() { long time = System.currentTimeMillis(); while(animationThread != null) { // Use a constant frame rate based on the system clock try { time += delay; Thread.sleep(Math.max(0, time - System.currentTimeMillis())); } catch (InterruptedException e) {} // initiate a repaint of the screen repaint(); } } public void paint(Graphics g) { // Clear the screen backGC.setColor(Color.yellow); backGC.fillRect(0,0,xsize,ysize); // Draw text backGC.setColor(Color.black); backGC.drawString(helloText, xOffset, yOffset); xOffset-=xspeed; if(xOffset <= 1) xspeed = -xspeed; if(xOffset+helloTextWidth >= xsize) xspeed = -xspeed; yOffset-=yspeed; if(yOffset <= 5) yspeed = -yspeed; if(yOffset+helloTextHeight >= ysize) yspeed = -yspeed; // Copy the backbuffer to the screen g.drawImage(backBuffer, 0, 0, this); } public void update(Graphics g) { paint(g); } }