1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.time.LocalTime; /** * Write a description of class Clock here. * * @author (your name) * @version (a version number or a date) */ public class Clock extends Actor { final float degrees06 = ( float ) (Math.PI / 30 ); final float degrees30 = degrees06 * 5 ; final float degrees90 = degrees30 * 3 ; final int size = 590 ; final int spacing = 100 ; final int diameter = size - 2 * spacing; final int cx = diameter / 2 + spacing; final int cy = diameter / 2 + spacing; public Clock() { } /** * Act - do whatever the Clock wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. GreenfootImage gfim = new GreenfootImage( 900 , 600 ); paintComponent(gfim); setImage(gfim); } public void paintComponent(GreenfootImage gfim) { drawFace(gfim); final LocalTime time = LocalTime.now(); int hour = time.getHour(); int minute = time.getMinute(); int second = time.getSecond(); float angle = degrees90 - (degrees06 * second); drawHand(gfim, angle, diameter / 2 - 30 , Color.RED); float minsecs = (minute + second / 60 .0F); angle = degrees90 - (degrees06 * minsecs); drawHand(gfim, angle, diameter / 3 + 10 , Color.BLACK); float hourmins = (hour + minsecs / 60 .0F); angle = degrees90 - (degrees30 * hourmins); drawHand(gfim, angle, diameter / 4 + 10 , Color.BLACK); } private void drawFace(GreenfootImage gfim) { //gfim.setStroke(new BasicStroke(2)); gfim.setColor(Color.WHITE); gfim.fillOval(spacing, spacing, diameter, diameter); gfim.setColor(Color.BLACK); gfim.drawOval(spacing, spacing, diameter, diameter); //setLocation(600,300); } private void drawHand(GreenfootImage gfim, float angle, int radius, Color color) { int x = cx + ( int ) (radius * Math.cos(angle)); int y = cy - ( int ) (radius * Math.sin(angle)); gfim.setColor(color); gfim.drawLine(cx, cy, x, y); } } |

