Slip No 8 Q B

Write a java program in multithreading using applet for Digital watch

package Multithread;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockSwing extends JFrame implements Runnable {

    Thread t;
    JLabel timeLabel;

    public ClockSwing() {
        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
        timeLabel.setForeground(Color.BLUE);
        timeLabel.setHorizontalAlignment(JLabel.CENTER);

        add(timeLabel);
        setTitle("Digital Clock");
        setSize(400, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                SimpleDateFormat formatter =
                        new SimpleDateFormat("hh:mm:ss a");
                String time = formatter.format(new Date());
                timeLabel.setText(time);

                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ClockSwing();
    }
}
// package Multithread;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockSwing extends JFrame implements Runnable {

    Thread t;
    JLabel timeLabel;

    public ClockSwing() {
        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
        timeLabel.setForeground(Color.BLUE);
        timeLabel.setHorizontalAlignment(JLabel.CENTER);

        add(timeLabel);
        setTitle("Digital Clock");
        setSize(400, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                SimpleDateFormat formatter =
                        new SimpleDateFormat("hh:mm:ss a");
                String time = formatter.format(new Date());
                timeLabel.setText(time);

                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ClockSwing();
    }
}
// Slip 8B
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top