1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| import javax.swing.*;
import java.awt.*;
import java.util.*;
public class PanneauDeDessin extends JPanel
{
public ThreadDeDessin thr = new ThreadDeDessin();
int large = 500;
int longu = 300;
int X1=large/2,
Y1=longu/2,
X2=large/2,
Y2=longu/2;
Graphics buffer;
Image image;
public PanneauDeDessin()
{
setPreferredSize(new Dimension(large, longu));
}
public void paintComponent(Graphics g)
{
if (buffer==null)
{
image = createImage(large, longu);
buffer = image.getGraphics();
buffer.setColor(Color.WHITE);
buffer.fillRect(0, 0, large, longu);
}
buffer.setColor( choixDUneCouleur() );
buffer.drawLine(X1,Y1,X2,Y2);
g.drawImage(image, 0, 0, this);
}
public void effacerEcran()
{
buffer.setColor(Color.WHITE);
buffer.fillRect(0,0,large,longu);
buffer.setColor(Color.BLACK);
repaint();
}
public Color choixDUneCouleur()
{
Random rand = new Random();
int R = rand.nextInt(255);
int G = rand.nextInt(255);
int B = rand.nextInt(255);
return new Color(R,G,B);
}
public void preparerProchainPoint()
{
Random rand = new Random();
X1 = X2;
Y1 = Y2;
X2 = rand.nextInt(large);
Y2 = rand.nextInt(longu);
}
public void demarrerThread()
{
thr.start();
}
public void arreterThread()
{
thr.setPaused(true);
}
public void reprendreThread()
{
thr.setPaused(false);
}
class ThreadDeDessin extends Thread
{
private boolean isPaused = false;
public void run()
{
Runnable task = new Runnable() {
public void run()
{
preparerProchainPoint();
repaint();
}
};
// Tant que le thread n'est pas interrompu
try {
while(true)
{
// On vérifie l'état de la pause (méthode bloquante) :
checkPause();
// On effectue les traitement
SwingUtilities.invokeLater(task);
sleep(100);
}
}
catch( InterruptedException e )
{
// En cas d'InterruptedException on sort de suite :
}
}
protected synchronized void checkPause() throws InterruptedException
{
if (isInterrupted())
{
// Si le thread est déjà interrompu, on provoque une exception :
throw new InterruptedException();
}
if (this.isPaused)
{
// Si on est en pause, on met le thread en attente :
// Le wait() libère le verrou du synchronized :
this.wait();
}
}
public synchronized void setPaused(boolean newValue)
{
isPaused = newValue;
if (!this.isPaused)
{
// Lorsqu'on enlève la pause, on envoit une notification au thread :
this.notify();
}
}
}
} |