|
 |
Lesson 03 |
|
Thread |
 |
 |
|
 |
|
[ Thread ]
In this tutorial you will learn how to use thread.
... Well, it is not so nice, it flickers a lot ... Why ?
=> I didn't use double buffering.
If you want to use double buffering now, go to lesson 4.
[ Code ]
// Lesson03
// Thread
// This code is better viewed with tab size=4
import java.applet.Applet;
import java.awt.*;
import java.net.*;
public class Lesson03 extends Applet implements Runnable
{
Color txtColor; // Text color
Image image; // Image
URL link; // Link
Thread thread; // Thread
int x,y; // Text position
boolean threadRunning; // thread running ?
boolean threadSuspended; // thread suspended ?
public void init()
{
txtColor = Color.white;
x = 10;
y = 20;
// Load Image
image=getImage(getDocumentBase(),getParameter("image"));
MediaTracker mediatracker = new MediaTracker(this);
mediatracker.addImage(image, 0);
try { mediatracker.waitForID(0); }
catch(InterruptedException ex) {}
mediatracker=null;
// Init link
try { link=new URL(getParameter("link")); }
catch (MalformedURLException e) { System.err.println(e); }
threadSuspended=false;
}
public void start() {
if(thread == null)
thread = new Thread(this);
threadRunning=true;
thread.start();
}
public void run()
{
while (threadRunning)
{
try
{
Thread.sleep(20); // sleep a while
synchronized(this)
{
while (threadSuspended) { wait(); } // thread suspended ?
}
}
catch(InterruptedException ex) {} // catch exception
x = (x+1)%200;
repaint(); // repaint will call update
}
}
public void stop() {
if(thread != null) {
threadRunning=false;
//thread.stop(); // this method has been deprecated
thread = null;
}
}
public void destroy()
{
}
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, this);
g.setColor(txtColor);
g.drawString("Lesson03",x-50,y);
}
public void update(Graphics g)
{
paint(g);
}
public synchronized boolean mouseEnter(Event event, int i, int j) {
threadSuspended=true; // Suspend thread
showStatus(link.toString()); // Show link in status bar
setCursor(new Cursor(Cursor.HAND_CURSOR)); // Change mouse cursor
return true;
}
public synchronized boolean mouseExit(Event event, int i, int j) {
threadSuspended=false; //
notify(); // notify
setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); // Change mouse cursor
return true;
}
public boolean mouseDown(Event event, int i, int j) {
getAppletContext().showDocument(link,"_blank"); // Open link
return true;
}
}
|
[ HTML TAG ]
<applet code="Lesson03.class" codebase = "lesson03" width="150" height="150">
<param name="image" value="lesson03/flare.jpg">
<param name="link" value="http://java.sun.com">
</applet>
|
[ Source ]
- Lesson.java
|
|
 |
|
 |
|
|