20
Clock
- // <applet code="Clock" width="200" height="100"></applet>
- import java.applet.Applet;
- import java.awt.*;
- import java.awt.event.*;
- public class Clock extends Applet implements Runnable, MouseListener {
- private volatile Thread thread = null;
- Color fg, bg;
- Font font;
- java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("HH:mm:ss");
- public void init() {
- bg = Color.BLUE;
- fg = Color.YELLOW;
- font = new Font("Sans-Serif", Font.BOLD, 36);
- setBackground(bg);
- addMouseListener(this);
- }
- public void start() {
- if (thread == null) {
- thread = new Thread(this, "Clock");
- thread.start();
- }
- }
- public void stop() {
- thread = null;
- }
- public void run() {
- while (this.thread == Thread.currentThread()) {
- repaint();
- try {
- Thread.sleep(1000);
- }
- catch (InterruptedException e) {
- }
- }
- }
- public void mouseClicked(MouseEvent e) {
- if (thread == null)
- start();
- else
- stop();
- }
- public void mouseEntered(MouseEvent e) {}
- public void mouseExited(MouseEvent e) {}
- public void mousePressed(MouseEvent e) {}
- public void mouseReleased(MouseEvent e) {}
- public void paint(Graphics g) {
- Dimension size = getSize();
- int width = size.width, height = size.height;
- Image offscreen = createImage(width, height);
- Graphics2D g2d = (Graphics2D) offscreen.getGraphics();
- g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- String s = formatter.format(new java.util.Date());
- g2d.setFont(font);
- FontMetrics fm = g2d.getFontMetrics();
- int x = (width - fm.stringWidth(s)) / 2;
- int y = (height - fm.getHeight()) / 2 + fm.getAscent();
- g2d.setColor(fg);
- g2d.drawString(s, x, y);
- g.drawImage(offscreen, 0, 0, this);
- }
- public void update(Graphics g) {
- paint(g);
- }
- }
$ javac Clock.java
$ appletviewer Clock.java
Click in the window to stop the clock. Click again to restart it.
Comments