>> Technologie Électronique >  >> Maison intelligente >> Vie connectée

Créer une horloge numérique en Java (Swing)

La bibliothèque Swing (Java SE) permet de construire facilement une interface graphique événementielle comme une horloge numérique. Composants clés : JFrame, JLabel, Timer, SimpleDateFormat, ActionListener.

Structure du code (DigitalClock.java)

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class DigitalClock extends JFrame implements ActionListener {
    private JLabel timeLabel;
    private SimpleDateFormat sdf;
    private Timer timer;

    public DigitalClock() {
        super();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        timeLabel = new JLabel();
        sdf = new SimpleDateFormat("HH:mm:ss");
        timeLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
        timeLabel.setFont(new Font("Dialog", Font.PLAIN, 24));

        timer = new Timer(500, this); // 0,5 s
        timer.setRepeats(true);
        timer.start();

        add(timeLabel);
        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == timer) {
            timeLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
        }
    }

    public static void main(String[] args) {
        new DigitalClock();
    }
}

Explications

  • JFrame : fenêtre principale.
  • JLabel : affiche l’heure.
  • SimpleDateFormat("HH:mm:ss") : format 24 h avec secondes.
  • Timer(500, this) : déclenche actionPerformed toutes les 500 ms.
  • ActionListener : met à jour le label avec l’heure système courante.

Compilez : javac DigitalClock.java ▸ Exécutez : java DigitalClock.

Vie connectée