Monday, 20 November 2017

Using java build a beautiful clock display current time

THIS IS THE CODE TO DISPLAY A BEAUTIFUL CLOCK

 package javaaa;

import java.awt.*;
import java.awt.geom.*;
 import java.awt.event.*;
 import java.util.Calendar;
 import javax.swing.*;

public class Javaaa extends JApplet {
 public static void main(String s[]) {
 JFrame frame = new JFrame();
 frame.setTitle("Clock");

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 JApplet applet = new Javaaa();
 applet.init();
 frame.getContentPane().add(applet);
 frame.pack();
 frame.setVisible(true);
 }

 public void init() {
 JPanel panel = new ClockPanel();
 getContentPane().add(panel);
 }
 }
 class ClockPanel extends JPanel implements ActionListener{
 AffineTransform rotH = new AffineTransform();
 AffineTransform rotM = new AffineTransform();
 AffineTransform rotS = new AffineTransform();

 public ClockPanel() {
 setPreferredSize(new Dimension(640, 480));
 setBackground(Color.white);
 Timer timer = new Timer(500, this);
 timer.start();
 }

 public void paintComponent(Graphics g) {
 super.paintComponent(g);
 Graphics2D g2 = (Graphics2D)g;
 Font currentFont = g2.getFont();
 g2.translate(320,240);
 // clock face
 Paint paint = new GradientPaint
 (-140,-140,Color.GREEN,-10,-10,Color.ORANGE);
 g2.setPaint(paint);
 g2.fillOval(-210, -210, 420, 420);
 g2.setColor(Color.red);
  Font newFont = currentFont.deriveFont(currentFont.getSize() * 3.4F);
            g2.setFont(newFont);
 g2.drawString("CLOCK", -70, 80);
 g2.setColor(Color.black);
  Font newFont1 = currentFont.deriveFont(currentFont.getSize() * 2.4F);
            g2.setFont(newFont1);
 g2.drawString("12", -18, -140);
 g2.drawString("3", 134, 19);
 g2.drawString("6", -8, 159);
 g2.drawString("9", -149, 20);
 Stroke stroke = new BasicStroke(3);
 g2.setStroke(stroke);
 g2.drawOval(-210, -210, 420, 420);
 for (int i = 0; i < 24; i++) {
 g2.rotate(2*Math.PI/12);
 if(i%2==0)
     g2.setColor(Color.BLUE);
 else
     g2.setColor(Color.red);
            
 g2.fill3DRect(-30, -200, 60, 30, true);
 }
 // clock hands
 Shape hour = new Line2D.Double(0, 0, 0, -100);
 hour = rotH.createTransformedShape(hour);
 Shape minute = new Line2D.Double(0, 0, 0, -140);
 minute = rotM.createTransformedShape(minute);
 Shape second = new Line2D.Double(0, 0, 0, -170);
 second = rotS.createTransformedShape(second);
 g2.setColor(Color.MAGENTA);
 g2.setStroke(new BasicStroke(10,
 BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
 g2.draw(hour);
 g2.draw(minute);
 g2.setStroke(new BasicStroke(4));
 g2.draw(second);
 }
 public void actionPerformed(ActionEvent e) {
 int hour = Calendar.getInstance().get(Calendar.HOUR);
 int min = Calendar.getInstance().get(Calendar.MINUTE);
 int sec = Calendar.getInstance().get(Calendar.SECOND);
 rotH.setToRotation(Math.PI * (hour+min/60.0)/6.0);
 rotM.setToRotation(Math.PI * min /30.0);
 rotS.setToRotation(Math.PI * sec /30.0);
 repaint();
}}

OUTPUT