Java編程——數字時鐘

來源:互聯網
上載者:User

標籤:kde   進程   對象   print   com   ram   roman   frame   util   

//ClockDemo.java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.awt.*;
import java.util.*;
import javax.swing.*;

//數字時鐘
public class ClockDemo extends JFrame implements Runnable{
Thread clock;

public ClockDemo(){
super("數字時鐘");//調用父類建構函式
setFont(new Font("Times New Roman",Font.BOLD,60));//設定時鐘的顯示字型
start(); //開始進程
setSize(280,100); //設定視窗尺寸
setVisible(true); //視窗可視
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉視窗時退出程式
}

public void start(){ //開始進程
if (clock==null){ //如果進程為空白值
clock=new Thread(this); //執行個體化進程
clock.start(); //開始進程
}
}

public void run(){ //運行進程
while (clock!=null){
repaint(); //調用paint方法重繪介面
try{
Thread.sleep(1000); //線程暫停一秒(1000毫秒)
}
catch (InterruptedException ex){
ex.printStackTrace(); //輸出出錯資訊
}
}
}

public void stop(){ //停止進程
clock=null;
}

public void paint(Graphics g){ //重載組件的paint方法
Graphics2D g2=(Graphics2D)g; //得到Graphics2D對象
Calendar now=new GregorianCalendar(); //執行個體化日曆對象
String timeInfo=""; //輸出資訊
int hour=now.get(Calendar.HOUR_OF_DAY); //得到小時數
int minute=now.get(Calendar.MINUTE); //得到分數
int second=now.get(Calendar.SECOND); //得到秒數

if (hour<=9)
timeInfo+="0"+hour+":"; //格式化輸出
else
timeInfo+=hour+":";
if (minute<=9)
timeInfo+="0"+minute+":";
else
timeInfo+=minute+":";
if (second<=9)
timeInfo+="0"+second;
else
timeInfo+=second;

g.setColor(Color.white); //設定使用中色彩為白色
Dimension dim=getSize(); //得到視窗尺寸
g.fillRect(0,0,dim.width,dim.height); //填充背景色為白色
g.setColor(Color.orange); //設定使用中色彩為橙色
g.drawString(timeInfo,20,80); //顯示時間字串
}

public static void main(String[] args){
new ClockDemo();
}
}

 

Java編程——數字時鐘

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.