`
zeyuphoenix
  • 浏览: 58858 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java的简单数字时钟

 
阅读更多
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 12"> <meta name="Originator" content="Microsoft Word 12"> <link rel="File-List" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> <link rel="Edit-Time-Data" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_editdata.mso"> <!--[if !mso]> <style> v":* {behavior:url(#default#VML);} o":* {behavior:url(#default#VML);} w":* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--><link rel="themeData" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> <link rel="colorSchemeMapping" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml"> <!--[if gte mso 9]><xml> Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 </xml><![endif]--><!--[if gte mso 9]><![endif]--><style> <!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1;} @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face {font-family:Calibri; panose-1:0 0 0 0 0 0 0 0 0 0; mso-font-alt:"Times New Roman";} @font-face {font-family:""@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal { mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; font-size:10.5pt; font-family:"Calibri","serif"; mso-bidi-font-family:"Times New Roman";} .MsoChpDefault { font-size:10.0pt;} /* Page Definitions */ @page {} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; layout-grid:15.6pt;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable { mso-style-parent:""; font-size:10.5pt; font-family:"Calibri","serif"; mso-bidi-font-family:"Times New Roman";} </style> <![endif]-->

Java的简单数字时钟

这里是最简单的实现方法,大概思路就是在一个JComponent上每隔一段时间进行一次重绘,为了保证重绘Timer的执行时间和终了时间,重写JComponentaddNotify方法和removeNotify方法,最后在DigitalClockUI中重写paint方法来绘制界面,并且重写 getPreferredSize使绘制的内容自适应界面的大小.

先看看效果:



<!--[if gte vml 1]> <![endif]-->

<!--[if gte vml 1]> <![endif]-->

基本的工程目录如下:

<!--[if gte vml 1]> <![endif]-->

首先是最基本的界面: Clock,在这个工程里,这个类作用很小,定义不定义其实都无所谓,这儿定义它主要是为了统一,为以后实现其它时钟提供方便

这儿把它定义成抽象的

/**

 * This bean to define basic properties and behaviors of a clock, concrete

 * instances will be implemented by <code>DigitalClock</code> and others.

 */

publicabstractclass Clock extends JComponent {

为它提供几个属性:

    /**

     * The calendar instance for this clock.

     */

    private Calendar calendar;

    /**

     * Background image of the clock.

     */

    private Image bgImage;

    /**

     * Font rendering context - assumes no default transform, anti-aliasing

     * active and fractional metrics allowed.

     */

publicstaticfinal FontRenderContext frc = new FontRenderContext(null, true, true);

其中FontRenderContext提供了文本显示和绘制的信息容器.

在构造函数中把calendar初始化:

    calendar = Calendar.getInstance();

接着看DigitalClock,这个类继承Clock,主要是提供时钟计时Timer启动和终止的,另外提供了数字时钟的页面分隔符信息,以及UI设置和取得.

首先是定义的属性:

    /**

     * divide time.

     */

    private String padding1 = "";

    private String padding2 = "";

分别代表时分秒之间的分隔和秒与毫秒之间的分隔.

接着是构造函数,提供基本的和带参数的两种:

    /**

     * Default construct: Uses default format and appearance.

     */

    public DigitalClock() {

       super();

       setFont(new Font("Arial", Font.BOLD, 20));

       setOpaque(true);

       padding1 = ":";

       padding2 = ".";

       setUI(DigitalClockUI.createUI(this));

    }

    /**

* Constructor: Initializes a digital-type clock by using given *parameters.

     */

    public DigitalClock(String padding1, String padding2, Font font,

           Color fg, Color bg, Locale locale) {

通过setUI(DigitalClockUI.createUI(this));把新的自定义UI赋给JComponent.

最后通过addNotifyremoveNotify方法复写启动和终止计时Timer

    /**

     * Invoked when panel is added to a container.

     */

    @Override

    publicvoid addNotify() {

       super.addNotify();

       getUI().start();

    }

    /**

     * Invoked when panel is removed from a container.

     */

    @Override

    publicvoid removeNotify() {

       getUI().stop();

       super.removeNotify();

    }

最后就是DigitalClockUI类了,它主要提供页面的绘制,计时Timer的管理和时间的计算以及界面大小的调整功能.

首先是继承关系:

publicclass DigitalClockUI extends PanelUI implements ActionListener {

它通过继承PanelUI(其实就是ComponentUI)实现时钟界面UI管理,实现ActionListener接口则是为了SwingTimer.

在构造函数中,Timer启动   

// stopwatch

       timer = new Timer(10, this);

仿照其他Component组件提供UI代理,使界面可以设置UI:

// Create an instance of the UI delegate for this component

    publicstatic ComponentUI createUI(DigitalClock component) {

       returnnew DigitalClockUI(component);

    }

然后定义类使用的属性:

    // Attributed string containing current time

    protected AttributedString timeString = null;

    // Text layout of attributed string

    protected TextLayout textLayout = null;

    // Attributed string containing current timezone.

    protected AttributedString timezoneString = null;

    // Text layout of attributed timezone.

    protected TextLayout textTimezoneLayout = null;

分别定义了绘制时间和时区的字符串属性格式和布局.

当组件加入到容器中呈现时,Timer启动,actionPerformed将会被调用.

    @Override

    publicvoid actionPerformed(ActionEvent event) {

在这个方法里,取得当前时间:

       // Create a new attributed string with the new time

       Date current = new Date();

       Calendar cal = panel.getCalendar();

       cal.setTime(current);

通过SimpleDateFormat类把时间格式化:

    // Hour24 mode

       df = new SimpleDateFormat("HH" + panel.getPadding1() + "mm"

              + panel.getPadding1() + "ss", panel.getLocale());

       // Draw AM/PM

       int tmpLen2 = 0;

       // mode

       df.applyPattern("a");

       // timezone

       df.applyPattern("Z");

       StringBuffer sb = new StringBuffer("GMT");

       sb.append(df.format(current));

       sb.insert(6, ":");

       df.applyPattern("zzzz");

然后将格式化好的时间字符串通过AttributedString设置显示格式:

timeString = new AttributedString(str);

// Render main time area

timeString.addAttribute(TextAttribute.FONT, font, 0, 6 + 2 * panel

              .getPadding1().length());

timeString.addAttribute(TextAttribute.FOREGROUND,panel.getForeground());

// Do blinking if reach alarm point

timeString.addAttribute(TextAttribute.FOREGROUND,

              panel.getForeground(), 0, 6 + 2 * panel.getPadding1().length());

// Render padding1, do blinking

timeString.addAttribute(TextAttribute.FOREGROUND, blink == 0 ? panel

              .getForeground() : panel.getBackground(), 2, 2 + panel

              .getPadding1().length());

timeString.addAttribute(TextAttribute.FOREGROUND, blink == 0 ? panel

              .getForeground() : panel.getBackground(), 2 + panel

              .getPadding1().length() + 2, 4 + 2 * panel.getPadding1()

              .length());

然后设置TextLayout

       // Create a new text layout and signal the panel that it needs

       // repainting

       textLayout = null;

       textLayout = new TextLayout(timeString.getIterator(), Clock.frc);

最后根据字符串大小设置组件大小,刷新

    // To keep the clock size fit for

       // actual size in time.

       panel.setSize(getPreferredSize(panel));

       panel.repaint();

       current = null;

       df = null;

最后一个方法是复写getPreferredSize使组件可以自适应大小

    // Return the preferred size for the component

    @Override

    public Dimension getPreferredSize(JComponent c) {

首先得出两个字符串大小:

Dimension size1 = textLayout.getBounds().getBounds().getSize();

Dimension size2 = textTimezoneLayout == null ? null : textTimezoneLayout.getBounds().getBounds().getSize();

然后宽度取2者大的,再额外增加一点Border

int max = width1;

       if (width2 > max)

           max = width2;

       size.width = max + MARGIN + 2;

高度选取2者之和加上两者间的间隙:

int height1 = (int) (textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading());

int height2 = (int) (textTimezoneLayout == null ? 0 : textTimezoneLayout.getAscent()+ textTimezoneLayout.getDescent() + textTimezoneLayout.getLeading());

size.height = (height1 + MARGIN) + (height2 + MARGIN);

到此为止,最简单的数字时钟就完成了.

通过

private DigitalClock getDigitalClock() {

    if (digitalClock == null) {

       // To create a digital-type clock with dark

       // red foreground and black background.

       digitalClock = new DigitalClock(":", "'", new Font("Comic Sans MS",Font.BOLD, 20), Color.GREEN.darker(), Color.BLACK

                  .brighter(), Locale.ENGLISH);

       }

       returndigitalClock;

    }

取得数字时钟组件,然后就和一般Java组件一样使用了.

分享到:
评论

相关推荐

    java 实现数字时钟 实例代码

    这个简单的Java程序创建了一个数字时钟,每秒自动更新一次时间。时钟以24小时格式显示小时、分钟和秒。通过`TimerTask`和`Timer`,我们可以定期执行特定任务,例如在这个例子中,是更新时钟显示。`JLabel`的文本颜色...

    数字时钟java源码

    这个简单的数字时钟程序虽然小巧,但它整合了Java编程中的多个重要概念,对于初学者来说是一个很好的实践项目。通过这个项目,开发者不仅可以学习到Java的基础知识,还能了解到如何构建GUI程序以及如何处理多线程,...

    Java模拟时钟和数字时钟代码

    在Java编程语言中,模拟时钟和数字时钟的实现涉及到多线程、图形用户界面(GUI)以及时间处理等核心概念。以下是对这些知识点的详细讲解: **1. Java多线程** Java中的多线程是实现时钟类的关键,因为时钟需要在一...

    Java模拟数字时钟

    Java窗口程序模拟的数字时钟特效。GregorianCalender类是Calender类的一个具体子类,提供了世界上大多数国家和地区使用的标准日历系统。可将本项目直接导入Eclipse或MyE运行ElectronicClock类,生成效果。

    java数字时钟

    以上代码创建了一个简单的Java数字时钟,它每秒钟更新一次时间并显示在窗口中。然而,实际应用中,为了提高性能和避免阻塞UI线程,通常会使用`javax.swing.Timer`而不是`Thread.sleep()`。 总结起来,Java数字时钟...

    Java练手_电子时钟

    在本项目"Java练手_电子时钟"中,我们主要关注的是如何使用Java编程语言来实现一个实时更新的数字时钟。这个练习涉及到多个Java技术领域,包括Java线程、AWT(Abstract Window Toolkit)绘图库以及Swing组件库。下面...

    一个简易的JAVA数字时钟支持24时12时转换

    这个项目名为"一个简易的JAVA数字时钟支持24时12时转换",它提供了在12小时制和24小时制之间切换的功能。根据描述,这个时钟程序已经经过了指导老师的调试,并且在某些JAVA版本下是可以正常运行的。如果你遇到任何...

    Android Studio编写的简单数字时钟

    9. **时间处理**: 更新数字时钟需要获取当前系统时间,Android提供了java.util.Calendar和java.text.SimpleDateFormat类来处理日期和时间的格式化。 10. **性能优化**: 为了保证时钟的流畅运行,应该避免过于频繁的...

    java简易时钟

    在Java编程中,创建一个简易时钟涉及到许多基础和进阶概念。首先,我们要了解Java中的定时器(Timer)和事件监听(Event Listener)机制,这两个是实现动态更新时间的关键。下面将详细解释这些知识点。 1. **Java ...

    java时钟_表盘数字

    数字时钟则相对简单,可能使用`JLabel`或者自定义组件来显示24小时制或12小时制的时间。可以使用`SimpleDateFormat`或`DateTimeFormatter`来格式化日期和时间字符串。 6. **事件监听**: 考虑到用户交互,可能...

    java日历与时钟

    在Java编程语言中,日历(Calendar)和时钟(Clock)是处理...通过理解和熟练使用Java的`java.time`包,开发者能够更加精确和高效地处理日期和时间相关的任务,无论是简单的日历模拟还是复杂的时区转换,都能游刃有余。

    数字时钟,java实现。

    这个简单的数字时钟程序会每秒打印一次当前时间,格式为`小时:分钟:秒`。注意,由于Java的`Thread.sleep(1000)`方法可能会被打断,所以捕获了`InterruptedException`。 为了增强时钟的功能,你可以考虑以下几点改进...

    Java设计简单时钟

    在Java编程中,设计一个简单的时钟涉及到对时间的处理和图形用户界面(GUI)的构建。本项目中,我们可以通过使用Java Swing库来创建一个动态显示当前时间的时钟应用。下面,我们将深入探讨这个Java时钟设计的相关...

    Java实现的简单数字时钟功能示例

    Java实现的简单数字时钟功能示例 Java实现的简单数字时钟功能示例主要介绍了Java实现的简单数字时钟功能,涉及java日期时间及JFrame框架图形界面操作相关实现技巧。下面将详细介绍该示例的知识点: 知识点一:...

    Java简单时钟(awt)

    在这个“Java简单时钟(AWT)”的例子中,我们将深入探讨这两个库在构建一个模拟石英钟的应用中的应用,同时还会涉及到系统托盘功能的实现。 **AWT与Swing** AWT是Java的原始GUI库,它提供了基本的窗口组件,如按钮...

    圆形数字时钟特效

    【标题】"圆形数字时钟特效"是一种网页设计中的元素,它通过数字形式展示时间,同时结合了圆形的视觉设计,使得时钟看起来既独特又时尚。这种特效常见于各类网站,尤其是那些注重用户体验和界面设计感的网页,能够...

    数字时钟 Clock Demo Clock Demo

    总之,"Clock Demo"是一个展示如何在Java环境中创建数字时钟的实例。通过学习和理解这个示例,开发者可以掌握如何处理时间数据,以及如何实现定时更新的机制,这对任何Java程序员来说都是重要的基础技能。

    java编写的时钟程序

    你可以通过重写`paintComponent()`方法来实现自定义绘图,如画出时钟的数字、指针等。 5. **线程处理**:为了让时钟持续更新时间,需要创建一个单独的线程来负责刷新界面。这通常通过继承`javax.swing.Timer`类或...

    Java_simpleclock.rar_java 时钟_时钟_时钟 java

    总的来说,这个Java简单时钟程序是一个很好的学习实例,它涵盖了基础的Java编程概念,如类、对象、线程和日期时间处理。通过分析和理解这个程序,开发者可以加深对Java语言的理解,并能应用到自己的项目中。如果你...

    用java编写的时钟小程序

    本文将详细介绍一个使用Java Applet编写的简单时钟程序。该程序能够显示一个动态的时钟模拟画面,实时更新时间显示,并且能够在浏览器中运行。我们将从代码结构、关键类与方法的使用、时间处理逻辑以及图形绘制等...

Global site tag (gtag.js) - Google Analytics