private?Shape?rect;????????????//背景矩形
專注于為中小企業(yè)提供成都網(wǎng)站制作、成都做網(wǎng)站、外貿(mào)營銷網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)碾子山免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了成百上千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
private?Font?font;????????????//設(shè)置字體
private?Date?date;????????????//現(xiàn)在的時間
private?Thread?time;????????//時間線程
private?CanvasPanel?canvas;
public?static?void?main(String[]?args)?{
new?TimerTest20140930();
}
public?TimerTest20140930(){
super("繪制文本");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
rect?=?new?Rectangle2D.Double(10,10,200,100);
font?=?new?Font("宋體",Font.BOLD,16);
canvas=new?CanvasPanel();
add(canvas);
time?=?new?Thread(new?Runnable(){
public?void?run(){
while(true){
canvas.repaint();
try{
Thread.sleep(1000);
}catch(Exception?ex){
}
}
}
});
time.start();
setLocationRelativeTo(null);
setVisible(true);
}??
class?CanvasPanel?extends?Canvas?{
public?void?paint(Graphics?g){
super.paint(g);
Graphics2D?g2?=?(Graphics2D)?g;
g2.setColor(Color.BLACK);
g2.fill(rect);
g2.setColor(Color.BLUE);
g2.setFont(font);
g2.drawString("現(xiàn)在的時間是",?20,?30);
date?=?new?Date();
g2.drawString(String.format("%tr",?date),?50,?60);???????
}
}
我之前倒是寫過這么一個,是放在某個類里作為私有類實現(xiàn)的,當(dāng)然你可以改為一個public的,下面是我的代碼,供參考
//私有類,實現(xiàn)時間的實時顯示
private?class?DisplayTime?extends?Thread ???//利用線程實現(xiàn)實時顯示
{
SimpleDateFormat?sdf=new?SimpleDateFormat("HH:mm:ss");????? ???//24小時制,精確到秒
public?void?run()
{
while(true)
{
time.setText(sdf.format(new?Date()));
try
{
Thread.sleep(1000); ???//線程休眠一秒
}
catch(InterruptedException?e)
{}
}
}
}
下面這個只能實現(xiàn)每按下一次按鈕顯示一次時間,動態(tài)的要用到Timer,本人新手那個做不來
import java.applet.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends Applet implements ActionListener{
private Label l;
public String times;
private Button b1;
public Date d;
public void init(){
l=new Label("");
b1=new Button("showtime");
d=new Date();
SimpleDateFormat from = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
times = from.format(d);
add(b1);
add(l);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
{
l.setText(times);
}
}
}