MAKING A DIGITAL CLOCK IN JAVA
Does making a Digital Clock in Java sounds cool to you? If yes then you, my friend definitely are in the place.
SOURCE CODE
- import java.awt.Font;
- import java.awt.Color;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.Timer;
- import javax.swing.SwingConstants;
- import java.util.*;
- import java.text.*;
- public class Clock
- {
- public static void main(String[] args)
- {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JFrame frame = new JFrame("Digital Clock");
- frame.setSize(300,150);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setLayout(new GridLayout(3, 1));
- ClockLabel dateL = new ClockLabel("date");
- ClockLabel timeL = new ClockLabel("time");
- ClockLabel dayL = new ClockLabel("day");
- frame.add(dateL);
- frame.add(timeL);
- frame.add(dayL);
- frame.getContentPane().setBackground(Color.decode("#005B5C"));
- frame.setVisible(true);
- }
- }
- @SuppressWarnings("serial")
- class ClockLabel extends JLabel implements ActionListener
- {
- String clockType;
- SimpleDateFormat format;
- public ClockLabel(String clockType) {
- this.clockType = clockType;
- setForeground(Color.white);
- if(clockType.equals("time"))
- {
- format = new SimpleDateFormat(" MMMM dd yyyy");
- setFont(new Font("monopaced", Font.ITALIC, 12));
- setHorizontalAlignment(SwingConstants.LEFT);
- }
- else if(clockType.equals("time"))
- {
- format = new SimpleDateFormat("hh:mm:ss a");
- setFont(new Font("monospaced", Font.ITALIC, 40));
- setHorizontalAlignment(SwingConstants.CENTER);
- }
- else if(clockType.equals("day"))
- {
- format = new SimpleDateFormat("EEEE ");
- setFont(new Font("monospaced", Font.ITALIC, 12));
- setHorizontalAlignment(SwingConstants.RIGHT);
- }
- else
- {
- format = new SimpleDateFormat();
- }
- }
- Timer timer = new Timer(1000, this);
- timer.start();
- }
- public void actionPerformed(ActionEvent event) {
- Date date = new Date();
- setText(format.format(date));
- }
- }
( If you like the content here, follow TSP on social media to get notified on future updates)
Comments
Post a Comment