import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.BorderFactory; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JPanel; class ThreadSimple extends Thread { int r = 10, debut; boolean continuer; boolean finir; JPanel panneauDisque; ThreadSimple(int debut, JPanel panneauDisque) { this.debut = debut; this.panneauDisque = panneauDisque; } void suspendre() { continuer = false; } synchronized void reprendre() { continuer = true; notify(); } synchronized void stopper() { finir = true; notify(); } public void run() { Graphics g = panneauDisque.getGraphics(); continuer = true; finir = false; for (int i = 0; i < 30; i++) { try { sleep(200); synchronized(this) { while (!continuer && !finir)wait(); } } catch (InterruptedException exc) {} if (finir) break; g.setColor(new Color((debut+528424*i)%Integer.MAX_VALUE)); g.drawOval(200 - r, 150 - r, 2*r, 2*r); r+=2; } } } @SuppressWarnings("serial") class PanneauThreadSimple extends JPanel implements ActionListener { ThreadSimple thread = null; Random alea; JButton tracer = new JButton("tracer"); JButton pauser = new JButton("pauser"); JButton stopper = new JButton("stopper"); JButton effacer = new JButton("effacer"); JPanel panneauDisque = new JPanel(); PanneauThreadSimple() { setLayout(new BorderLayout(5, 5)); JPanel panneauBouton = new JPanel(); panneauDisque.setPreferredSize(new Dimension(400,300)); tracer.addActionListener(this); pauser.addActionListener(this); stopper.addActionListener(this); effacer.addActionListener(this); panneauBouton.add(tracer); panneauBouton.add(pauser); panneauBouton.add(stopper); panneauBouton.add(effacer); add(panneauBouton, BorderLayout.NORTH); add(panneauDisque, BorderLayout.CENTER); alea = new Random(System.currentTimeMillis()); setBorder(BorderFactory.createLineBorder(Color.BLACK)); } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == tracer) { int debut= (int)Math.abs(alea.nextLong()); if ((thread == null)||(!thread.isAlive())) { thread = new ThreadSimple(debut, this); thread.start(); } else thread.reprendre(); } else if ((source == pauser) && (thread != null)) thread.suspendre(); else if (source == stopper) { if (thread != null) thread.stopper(); thread = null; } else if (source == effacer) repaint(); } } @SuppressWarnings("serial") public class EssaiThreadSimpleA extends JApplet { public void init() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { PanneauThreadSimple ihm = new PanneauThreadSimple(); ihm.setBorder(BorderFactory.createLineBorder(Color.BLACK)); setLayout(new FlowLayout(FlowLayout.CENTER)); add(ihm); } }); } catch (Exception e) { System.err.println("Impossible de lancer correctement l'applet"); } } }