- /**
- * <p>Copyright: Copyright (c) 2002-2004</p>
- * <p>Company: JavaResearch(http://www.javaresearch.org)</p>
- * <p>最后更新日期:2003年5月7日
- * @author cherami
- */
- package org.jr.swing;
-
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.text.*;
- import java.util.Date;
-
- /**
- * 数字钟。
- * 可以以一定的格式显示时间。
- * @since 0.6
- */
-
- public class DigitClock
- extends JLabel {
- DateFormat format;
- Timer timer;
- Date now;
- public static final DateFormat defaultFormat = DateFormat.getTimeInstance(
- DateFormat.MEDIUM);
- /**
- * 以缺省的格式构造一个DigitClock。
- */
- public DigitClock() {
- this(defaultFormat);
- }
-
- /**
- * 以指定的格式构造一个DigitClock。
- * @param format 格式
- */
- public DigitClock(DateFormat format) {
- timer = new Timer(1000, new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- now = new Date();
- repaint();
- }
- });
- timer.start();
- this.format = format;
- }
-
- /**
- * 设置时间显示的格式。
- * @param format 格式
- */
- public void setFormat(DateFormat format) {
- this.format = format;
- }
-
- /**
- * 得到当前的格式。
- * @return 当前使用的时间格式
- */
- public DateFormat getFormat() {
- return format;
- }
-
- /**
- * 得到组件的最适合的大小。
- * @return 组件的最适合的大小
- */
- public Dimension getPreferredSize() {
- Graphics g = getGraphics();
- FontMetrics fontMetrics = g.getFontMetrics();
- int height = fontMetrics.getHeight() + 5;
- int width = fontMetrics.stringWidth(format.format(now)) + 10;
- return new Dimension(width, height);
- }
-
- /**
- * 重新绘制组件。
- * @param g 图形设备
- */
- protected void paintComponent(Graphics g) {
- String time = format.format(now);
- FontMetrics fontMetrics = g.getFontMetrics();
- Dimension size = getSize();
- int height = size.height;
- int width = size.width;
- int x = (width - fontMetrics.stringWidth(time)) / 2;
- int y = height / 2;
- g.drawString(time, x, y);
- }
-
- /**
- * 重新开始运动显示。
- */
- public void start() {
- timer.start();
- }
-
- /**
- * 停止运动。
- */
- public void stop() {
- timer.stop();
- }
- }