Here, it should be a very simple program. When the mouse is clicked, it toggles a boolean value named hello. if hello is true, it draws hello on the screen. But it doesnt work, this mouse stuff is tricky. I click on the screen and nothing happens. Does it has to do with the thread?
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class MouseTest extends Applet implements Runnable, MouseListener, MouseMotionListener
{
Thread loop;
BufferedImage backbuffer;
Graphics g2d;
boolean hello;
public void init()
{
backbuffer = new BufferedImage(100,100, BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
}
public void start()
{
loop = new Thread(this);
loop.start();
hello = false;
}
public void run()
{
Thread t = Thread.currentThread();
while (t == loop)
{
try
{
Thread.sleep(30);
}
catch(InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
public void paint(Graphics g)
{
g.drawImage(backbuffer,0,0,this);
}
public void update(Graphics g)
{
if(hello)
g2d.drawString("Hello",2,10);
paint(g);
}
public void mousePressed(MouseEvent evt)
{
hello = !hello;
}
public void mouseReleased(MouseEvent evt) {}
public void mouseDragged(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseMoved(MouseEvent evt) { }
}
Anyone knows whats wrong?