import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Composant chronomètre (mm:ss) pour le jeu du pendu. * - Démarre/stoppe/réinitialise le temps * - S'affiche comme une barre en haut de la fenêtre * * @version 1.0 * @author Adrien * Date : 08-10-2025 * Licence : */ public class Chronometre extends JPanel implements ActionListener { private final JLabel timeLabel = new JLabel("00:00", SwingConstants.CENTER); private final Timer timer; // tick chaque seconde private boolean running = false; private long startMillis = 0L; private long accumulatedMillis = 0L; public Chronometre() { setLayout(new BorderLayout()); setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); timeLabel.setFont(new Font("Segoe UI", Font.BOLD, 20)); add(timeLabel, BorderLayout.CENTER); // Timer Swing (1s) timer = new Timer(1000, this); } /** Démarre le chronomètre (ou reprend si en pause). */ public void start() { if (!running) { running = true; startMillis = System.currentTimeMillis(); timer.start(); repaint(); } } /** Met en pause le chronomètre. */ public void stop() { if (running) { running = false; accumulatedMillis += System.currentTimeMillis() - startMillis; timer.stop(); repaint(); } } /** Remet le chronomètre à 00:00 (sans le relancer). */ public void reset() { running = false; startMillis = 0L; accumulatedMillis = 0L; timer.stop(); updateLabel(0L); } /** Temps écoulé total (en millisecondes). */ public long getElapsedMillis() { long now = System.currentTimeMillis(); long runningMillis = running ? (now - startMillis) : 0L; return accumulatedMillis + runningMillis; } /** Tick du timer : met à jour l'affichage. */ @Override public void actionPerformed(ActionEvent actionEvent) { updateLabel(getElapsedMillis()); } // --- interne --- private void updateLabel(long elapsedMillis) { long totalSeconds = elapsedMillis / 1000; long minutes = totalSeconds / 60; long seconds = totalSeconds % 60; timeLabel.setText(String.format("%02d:%02d", minutes, seconds)); } }