1. /**
  2. * <p>Copyright: Copyright (c) 2002-2004</p>
  3. * <p>Company: JavaResearch(http://www.javaresearch.org)</p>
  4. * <p>最后更新日期:2003年5月7日
  5. * @author cherami
  6. */
  7. package org.jr.swing;
  8. import javax.swing.*;
  9. import java.awt.*;
  10. import java.awt.event.*;
  11. import java.text.*;
  12. import java.util.Date;
  13. /**
  14. * 数字钟。
  15. * 可以以一定的格式显示时间。
  16. * @since 0.6
  17. */
  18. public class DigitClock
  19. extends JLabel {
  20. DateFormat format;
  21. Timer timer;
  22. Date now;
  23. public static final DateFormat defaultFormat = DateFormat.getTimeInstance(
  24. DateFormat.MEDIUM);
  25. /**
  26. * 以缺省的格式构造一个DigitClock。
  27. */
  28. public DigitClock() {
  29. this(defaultFormat);
  30. }
  31. /**
  32. * 以指定的格式构造一个DigitClock。
  33. * @param format 格式
  34. */
  35. public DigitClock(DateFormat format) {
  36. timer = new Timer(1000, new ActionListener() {
  37. public void actionPerformed(ActionEvent e) {
  38. now = new Date();
  39. repaint();
  40. }
  41. });
  42. timer.start();
  43. this.format = format;
  44. }
  45. /**
  46. * 设置时间显示的格式。
  47. * @param format 格式
  48. */
  49. public void setFormat(DateFormat format) {
  50. this.format = format;
  51. }
  52. /**
  53. * 得到当前的格式。
  54. * @return 当前使用的时间格式
  55. */
  56. public DateFormat getFormat() {
  57. return format;
  58. }
  59. /**
  60. * 得到组件的最适合的大小。
  61. * @return 组件的最适合的大小
  62. */
  63. public Dimension getPreferredSize() {
  64. Graphics g = getGraphics();
  65. FontMetrics fontMetrics = g.getFontMetrics();
  66. int height = fontMetrics.getHeight() + 5;
  67. int width = fontMetrics.stringWidth(format.format(now)) + 10;
  68. return new Dimension(width, height);
  69. }
  70. /**
  71. * 重新绘制组件。
  72. * @param g 图形设备
  73. */
  74. protected void paintComponent(Graphics g) {
  75. String time = format.format(now);
  76. FontMetrics fontMetrics = g.getFontMetrics();
  77. Dimension size = getSize();
  78. int height = size.height;
  79. int width = size.width;
  80. int x = (width - fontMetrics.stringWidth(time)) / 2;
  81. int y = height / 2;
  82. g.drawString(time, x, y);
  83. }
  84. /**
  85. * 重新开始运动显示。
  86. */
  87. public void start() {
  88. timer.start();
  89. }
  90. /**
  91. * 停止运动。
  92. */
  93. public void stop() {
  94. timer.stop();
  95. }
  96. }