時鍾java
㈠ java編寫世界時鍾
package Time;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class TimerTest extends JFrame{
TimerPanel tp;
TimerTest(){
setTitle("世界時鍾");
setSize(500,300);
tp=new TimerPanel();
Thread t=new Thread(tp);
t.start();
this.add(tp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TimerTest();
}
}
class TimerPanel extends JPanel implements Runnable{
Time[] t=new Time[6];
TimerPanel(){
t[0]=new Time(0,0,"北京",8);
t[1]=new Time(150,0,"巴黎",1);
t[2]=new Time(300,0,"華盛頓",8);
t[3]=new Time(0,150,"洛杉磯",5);
t[4]=new Time(150,150,"倫敦",0);
t[5]=new Time(300,150,"芝加哥",7);
setBackground(Color.black);
}
public void paint(Graphics g){
super.paint(g);
for(int i=0;i<t.length;i++)
t[i].draw(g);
}
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.repaint();
}
}
}
/*上面就不注釋了,下面的是Time類*/
class Time{
private int x,y;/*每個鍾表的坐標*/
private String place;/*每個鍾表的名字*/
private int timezone;/*每個鍾表的時區,東x區為+x,西x區為-x*/
private Date d;
private long time;
private double hour,minite,second;
Time(int x,int y,String place,int timezone){
this.x=x;
this.y=y;
this.place=place;
this.timezone=timezone;
}
public void draw(Graphics g){
g.setColor(Color.green);
d=new Date();
time=d.getTime();/*獲得0時區1970年1月1日0點到現在的毫秒數*/
hour=(((time/1000)+3600*timezone)%43200)*2*Math.PI/3600/12;/*計算時針弧度*/
minite=(time/1000)%3600*2*Math.PI/3600;/*計算分針弧度*/
second=(time/1000)%60*2*Math.PI/60;/*計算秒針弧度*/
/*畫出鍾表輪廓和時針*/
((Graphics2D)g).setStroke(new BasicStroke(3.0f));
((Graphics2D)g).drawOval(x, y, 100, 100);
((Graphics2D)g).drawLine(x+50, y, x+50, y+5);
((Graphics2D)g).drawLine(x+50, y+100, x+50, y+95);
((Graphics2D)g).drawLine(x, y+50, x+5, y+50);
((Graphics2D)g).drawLine(x+100,y+50, x+95, y+50);
((Graphics2D)g).drawLine(x+50,y+50,(int)(x+50+25*Math.sin(hour)),(int)(y+50-25*Math.cos(hour)));
/*畫出分針*/
((Graphics2D)g).setStroke(new BasicStroke(2.0f));
((Graphics2D)g).drawLine(x+50,y+50,(int)(x+50+35*Math.sin(minite)),(int)(y+50-35*Math.cos(minite)));
/*畫出秒針*/
((Graphics2D)g).setStroke(new BasicStroke(1.0f));
((Graphics2D)g).drawLine(x+50,y+50,(int)(x+50+45*Math.sin(second)),(int)(y+50-45*Math.cos(second)));
/*畫出鍾表名字*/
g.setColor(Color.red);
g.drawString(place, x+35, y+120);
}
}
寫了好久,把分給我吧~~
㈡ 怎麼用java編寫時鍾呀
import
java.util.*;
import
java.awt.*;
import
java.applet.*;
//impelements
Runnable
是線程程序的介面
public
class
Clock
extends
Applet
implements
Runnable
{
Thread
timer
=
null;
//
定義線程實體timer
int
xcenter
=
400,
ycenter
=
50;
int
Radius
=
ycenter
-
5;
public
void
init()
{
resize(400,
125);//
設置時鍾程序的窗口大小
setBackground(Color.white);//
設置小應用程序的背景色
}
public
void
paint(Graphics
g)
{
int
xh,
yh,
xm,
ym,
xs,
ys,
s,
m,
h;
String
today;
Date
dat
=
new
Date();
//
定義時間類dat
s
=
dat.getSeconds();
//
獲得時間秒
m
=
dat.getMinutes();
//
獲得時間分
h
=
dat.getHours();
today
=
dat.toLocaleString();
//
獲得字元串時間格式
g.clearRect(0,
0,
size().width,
size().height);
//
消除小應用程序
xcenter
=
xcenter
-
1;
//
向左移動一個像素點
if
(xcenter
<
-50)
xcenter
=
400;
//
如果xcenter小於-50,則回到初始位置
//
計算秒的坐標
xs
=
(int)
(Math.cos(s
*
3.14f
/
30
-
3.14f
/
2)
*
(Radius
-
5)
+
xcenter);
ys
=
(int)
(Math.sin(s
*
3.14f
/
30
-
3.14f
/
2)
*
(Radius
-
5)
+
ycenter);
//
計算分鍾的坐標
xm
=
(int)
(Math.cos(m
*
3.14f
/
30
-
3.14f
/
2)
*
(Radius
-
10)
+
xcenter);
ym
=
(int)
(Math.sin(m
*
3.14f
/
30
-
3.14f
/
2)
*
(Radius
-
10)
+
ycenter);
//
計算小時的坐標
xh
=
(int)
(Math.cos((h
*
30
+
m
/
2)
*
3.14f
/
180
-
3.14f
/
2)
*
(Radius
-
20)
+
xcenter);
yh
=
(int)
(Math.sin((h
*
30
+
m
/
2)
*
3.14f
/
180
-
3.14f
/
2)
*
(Radius
-
20)
+
ycenter);
g.setColor(Color.darkGray);
//
設置顏色
g.drawString("9",
xcenter
-
(Radius
-
5),
ycenter
+
3);
//
顯示時鍾上的數字『9』
g.drawString("3",
xcenter
+
(Radius
-
10),
ycenter
+
3);
//
顯示時鍾上的數字『3』
g.drawString("12",
xcenter
-
5,
ycenter
-
(Radius
-
13));
//
顯示時鍾上的數字'12'
g.drawString("6",
xcenter
-
3,
ycenter
+
(Radius
-
10));
//
顯示時鍾上的數字'6'
g.drawString(today,
0,
125);
//
顯示字元串時鍾
g.drawLine(xcenter,
ycenter,
xs,
ys);
//
畫秒針
g.setColor(Color.blue);
//
設置顏色
g.drawArc(xcenter
-
Radius,
ycenter
-
Radius,
2
*
Radius,
2
*
Radius,
0,
360);
//
畫鍾
g.drawLine(xcenter,
ycenter
-
1,
xm,
ym);
//
畫分針
g.drawLine(xcenter
-
1,
ycenter,
xm,
ym);
//
畫分針
g.drawLine(xcenter,
ycenter
-
1,
xh,
yh);
//
畫時針
g.drawLine(xcenter
-
1,
ycenter,
xh,
yh);
//
畫時針
}
public
void
start()
{
if
(timer
==
null)
{
timer
=
new
Thread(this);
//
生成Thread(多線程程序)的對象實體
timer.start();
//
啟動生成的線程
}
}
public
void
stop()
{
timer.stop();
//
停止線程的工作
timer
=
null;
//
放掉Thread對象
}
public
void
run()
//
改方法用來定義線程體,一旦線程被啟動執行,就開始執行這個方法
{
while
(timer
!=
null)
{
try
{
Thread.sleep(150);
//
使當前正在執行的線程進入睡眠時間由參數millis確定,
//
單位時間是毫秒,當這個時間過去,線程即可運行的
while
(timer
!=
null)
{
try
{
Thread.sleep(150);//
使用當前正在執行的線程進入睡眠時間由參數
//
millis確定,單位是毫秒,當這個時間過去,線程即為可運行的
}
catch
(InterruptedException
e)
{
}
repaint();
//
repaint所做的事其實是去調用方法uadate重畫效應用程序
}
timer
=
null;
}
catch
(InterruptedException
e)
{
}
}
}
//
所做的工作是先將整個效應用程序區域清除,再去調用paint,完成重畫的動作
public
void
update(Graphics
g)
{
paint(g);
}
}
㈢ java時鍾
GDI+時鍾
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class Clock extends JComponent {
private static final Color INTEGRAL_COLOR = new Color(0, 128, 128);
private int radius;
private Calendar currentTime = Calendar.getInstance();
private double s = 0.03;
public Clock(int radius) {
this.radius = radius;
}
public void setCurrentTime(Date time)
{
this.currentTime.setTime(time);
}
public void setCurrentTime(long millis) {
this.currentTime.setTimeInMillis(millis);
}
public Dimension getPreferredSize() {
Insets insets = getInsets();
int r = (int) (radius == -1 ? 0 : radius * (1 + s)) + 1;
return new Dimension(r * 2 + insets.left + insets.right, r * 2
+ insets.top + insets.bottom);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Insets insets = getInsets();
int wid = getWidth() - insets.left - insets.right;
int hei = getHeight() - insets.top - insets.bottom;
int r = (int) ((Math.min(wid, hei)) / 2 / (1 + s));
g2d.translate(insets.left + r * (1 + s), insets.top + r * (1 + s));
g2d.scale(1, -1);
for (int i = 0; i < 60; i++) {
int angle = 90 - i * 6;
double pos[] = calcPos(r, angle);
paintMinuteDot(r, g2d, pos[0], pos[1], i % 5 == 0);
}
paintHourPointer(r, g2d);
paintMinutePointer(r, g2d);
paintSecondPointer(r, g2d);
paintCenterPoint(g2d);
g2d.scale(1, -1);
g2d.translate(-insets.left - r * (1 + s), -insets.top - r * (1 + s));
}
private void paintCenterPoint(Graphics2D g2d) {
g2d.setColor(Color.BLUE);
Rectangle2D rect = new Rectangle2D.Double(-2, -2, 4, 4);
g2d.fill(rect);
}
private void paintMinutePointer(int r, Graphics2D g2d) {
int minute = currentTime.get(Calendar.MINUTE);
int second = currentTime.get(Calendar.SECOND);
double angle = 90 - (minute + second / 60.0) * 6;
Shape pointerShape = createPointerShape(r * 0.8, r * 0.04, r * 0.08,
angle);
g2d.setColor(Color.LIGHT_GRAY);
g2d.fill(pointerShape);
g2d.setColor(Color.DARK_GRAY);
g2d.draw(pointerShape);
}
private void paintHourPointer(int r, Graphics2D g2d) {
int hour = currentTime.get(Calendar.HOUR);
int minute = currentTime.get(Calendar.MINUTE);
int second = currentTime.get(Calendar.SECOND);
double angle = 90 - (hour + minute / 60.0 + second / 3600.0) * 30;
Shape pointerShape = createPointerShape(r * 0.6, r * 0.06, r * 0.1,
angle);
g2d.setColor(Color.LIGHT_GRAY);
g2d.fill(pointerShape);
g2d.setColor(Color.DARK_GRAY);
g2d.draw(pointerShape);
}
private Shape createPointerShape(double r1, double r2, double r3,
double angle) {
GeneralPath gp = new GeneralPath();
double[] pos = calcPos(r1, angle);
double[] pos1 = calcPos(r2, angle + 90);
gp.append(new Line2D.Double(pos[0], pos[1], pos1[0], pos1[1]), true);
double[] pos2 = calcPos(r3, angle + 180);
gp.lineTo((float) pos2[0], (float) pos2[1]);
double[] pos3 = calcPos(r2, angle + 270);
gp.lineTo((float) pos3[0], (float) pos3[1]);
gp.closePath();
return gp;
}
private void paintSecondPointer(int r, Graphics2D g2d) {
g2d.setColor(Color.BLACK);
int second = currentTime.get(Calendar.SECOND);
int angle = 90 - second * 6;
double pos[] = calcPos(r * 0.9, angle);
double pos1[] = calcPos(r * 0.2, angle + 180);
Line2D line = new Line2D.Double(pos1[0], pos1[1], pos[0], pos[1]);
g2d.draw(line);
}
private void paintMinuteDot(int r, Graphics2D g2d, double x, double y,
boolean flag) {
g2d.setColor(flag ? Color.RED : Color.BLACK);
if (flag) {
// Rectangle2D rect = new Rectangle2D.Double(
Ellipse2D rect = new Ellipse2D.Double(x - r * s, y - r * s, r * s
* 2, r * s * 2);
g2d.fill(rect);
} else {
// Rectangle2D rect = new Rectangle2D.Double(
Ellipse2D rect = new Ellipse2D.Double(x - r * 0.02, y - r * 0.02,
r * 0.04, r * 0.04);
g2d.fill(rect);
}
}
private double[] calcPos(double r, double angle) {
double radian = Math.toRadians(angle);
double x = r * Math.cos(radian);
double y = r * Math.sin(radian);
return new double[] { x, y };
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
final Clock clock = new Clock(50);
clock.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JFrame f = new JFrame("GDI+時鍾");
// f.setBounds(380,200,500,600);
f.this.add(clock, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
clock.setCurrentTime(System.currentTimeMillis());
clock.repaint();
}
}
}.start();
}
}
㈣ JAVA 編寫時鍾程序
分太少了啊
給你一個只實現了時鍾的面板。
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
public class Clock extends JFrame implements ActionListener
{
private static final long serialVersionUID = 6790815213225162093L;
Timer timer;
int x,y,old_X,old_Y, r,x0,y0,w,h,ang;
int sdo,mdo,hdo,old_M,old_H;
TimeZone tz =TimeZone.getTimeZone("JST");
final double RAD=Math.PI/180.0;
public Clock()
{
super("時鍾");
setSize(300,300);
setBackground(new Color(0,0,192));
setResizable(false);
Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();
Dimension fra=this.getSize();
if(fra.width>scr.width)
{
fra.width=scr.width;
}
if(fra.height>scr.height)
{
fra.height=scr.height;
}
this.setLocation((scr.width-fra.width)/2,(scr.height-fra.height)/2);
setVisible(true);
int delay = 1000;
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
repaint();
}
};
new Timer(delay, taskPerformer).start();
}
public void actionPerformed(ActionEvent e)
{
timer.restart();
}
public void paint( Graphics g )
{
Insets insets = getInsets();
int L0 = (insets.left)/2, T0 = (insets.top)/2;
int hh,mm,ss;
String st;
h=getSize().height;
g.setColor(Color.white);
g.drawOval(L0+30,T0+30,h-60,h-60);
g.drawOval(L0+32,T0+32,h-64,h-64);
r=h/2-30;
x0=30+r-5+L0;
y0=30+r-5-T0;
ang=60;
for (int i=1; i<=12; i++)
{
x=(int)((r+10)*Math.cos(RAD*ang)+x0);
y=(int)((r+10)*Math.sin(RAD*ang)+y0);
g.drawString(""+i,x,h-y);
ang-=30;
}
x0=30+r+L0; y0=30+r+T0;
Calendar now=Calendar.getInstance();
hh=now.get(Calendar.HOUR_OF_DAY);
mm=now.get(Calendar.MINUTE);
ss=now.get(Calendar.SECOND);
g.setColor(Color.pink);
g.fillRect(L0,T0,60,28);
g.setColor(Color.blue);
if (hh < 10) st="0"+hh; else st=""+hh;
if (mm < 10) st=st+":0"+mm; else st=st+":"+mm;
if (ss < 10) st=st+":0"+ss; else st=st+":"+ss;
g.drawString(st,L0,T0+25);
sdo=90-ss*6;
mdo=90-mm*6;
hdo=90-hh*30-mm/2;
if (old_X > 0)
{
g.setColor(getBackground());
g.drawLine(x0,y0,old_X,(h-old_Y));
} else
{
old_M=mdo;
old_H=hdo;
}
g.setColor(Color.yellow);
x=(int)((r-8)*Math.cos(RAD*sdo)+x0);
y=(int)((r-8)*Math.sin(RAD*sdo)+y0)-2*T0;
g.drawLine(x0,y0,x,(h-y));
old_X=x;
old_Y=y;
if (mdo != old_M)
{
line(g,old_M,(int)(r*0.7),getBackground());
old_M=mdo;
}
if (hdo != old_H)
{
line(g,old_H,(int)(r*0.5),getBackground());
old_H=hdo;
}
line(g,mdo,(int)(r*0.7),Color.green);
line(g,hdo,(int)(r*0.5),Color.red);
}
public void line(Graphics g, int t, int n, Color c)
{
int [] xp = new int[4];
int [] yp = new int[4];
xp[0]=x0;
yp[0]=y0;
xp[1]= (int)((n-10)*Math.cos(RAD*(t-4))+x0);
yp[1]=h-(int)((n-10)*Math.sin(RAD*(t-4))+y0);
xp[2]= (int)( n *Math.cos(RAD* t )+x0);
yp[2]=h-(int)( n *Math.sin(RAD* t )+y0);
xp[3]= (int)((n-10)*Math.cos(RAD*(t+4))+x0);
yp[3]=h-(int)((n-10)*Math.sin(RAD*(t+4))+y0);
g.setColor(c);
g.fillPolygon(xp,yp,4);
}
public static void main(String args[])
{
new Clock();
}
}
㈤ 怎樣用java 程序寫一個時鍾程序
面向對象思想寫成:
下面是一個顯示器類
publicclassDisplay{
privateintvalue;//現在的值
privateintlimit;//上限值
Display(intlimit){
this.limit=limit;
}
publicvoidincrease(){
value++;
if(value==limit){
value=0;
}
}
publicintgetValue(){
returnvalue;
}
publicstaticvoidmain(String[]args){
Displayd=newDisplay(24);
for(;;){
d.increase();
System.out.println(d.getValue());
}
}
}
下面創建一個時鍾對象:
publicclassClock{
privateDisplayh=newDisplay(24);
privateDisplaymin=newDisplay(60);
privateDisplays=newDisplay(60);
publicvoidstart(){
for(;;){
s.increase();
if(s.getValue()==0){//如果分重置,小時+1
min.increase();
if(min.getValue()==0){//如果分重置,小時+1
h.increase();
}
}
System.out.printf("%02d:%02d:%02d ",h.getValue(),min.getValue(),s.getValue());//格式輸出
}
}
publicstaticvoidmain(String[]args){
Clockclock=newClock();
clock.start();
}
㈥ JAVA時鍾代碼解釋
lz這個代碼有什麼看不懂的 如果這個代碼看不懂的話 建議你從基礎的開始學習吧
首先可以看到extends JFrame implements ActionListener 關於ActionListener 介面和JFrame 類lz有必要去看看 加入api慢慢研究下吧
int x,y,x0,y0,r,h,olds_x,olds_y,oldm_x,oldm_y,oldh_x,oldh_y,ss,mm,hh,old_m,old_h,ang;
這些東西我也看不懂 因為你的代碼不完整
final double RAD=Math.PI/180; 這個應該是算一個弧度吧
super("made by mcj and wdh"); 這句無意義 是父類的代碼
setDefaultCloseOperation(3);這個方法是什麼??代碼不完整
setSize(300,300);設置窗體大小
setBackground(Color.white);設置背景色
setLocation(300,150); 定位
setResizable(false);不調整大小
setVisible(true);可見
後面的就沒有代碼了
㈦ 用JAVA寫數字時鍾
importjavax.swing.*;
importjava.awt.event.ActionListener;
importjava.awt.event.ActionEvent;
importjava.awt.*;
importjava.util.Calendar;
importjava.util.GregorianCalendar;
{
intx,y,x0,y0,r,h,olds_x,olds_y,oldm_x,oldm_y,oldh_x,oldh_y,ss,mm,hh,old_m,old_h,ang;
finaldoubleRAD=Math.PI/180;
publicClock(){
super("Clockbykikiwawa");
setDefaultCloseOperation(3);
setSize(200,200);
setBackground(Color.BLACK);
setLocation(300,150);
setResizable(false);
setVisible(true);
intdelay=1000;
ActionListenerdrawClock=newActionListener(){
publicvoidactionPerformed(ActionEventevt){
repaint();
}
};
newTimer(delay,drawClock).start();
}
publicvoidactionPerformed(ActionEvente){
}
publicvoidpaint(Graphicsg){
Graphics2Dg2D=(Graphics2D)g;
Insetsinsets=getInsets();
intL=insets.left/2,T=insets.top/2;
h=getSize().height;
g.setColor(Color.white);
g2D.setStroke(newBasicStroke(4.0f));
g.drawOval(L+40,T+40,h-80,h-80);
r=h/2-40;
x0=40+r-5+L;
y0=40+r-5-T;
ang=60;
for(inti=1;i<=12;i++){
x=(int)((r+10)*Math.cos(RAD*ang)+x0);
y=(int)((r+10)*Math.sin(RAD*ang)+y0);
g.drawString(""+i,x,h-y);
ang-=30;
}
Calendarnow=newGregorianCalendar();
intnowh=now.get(Calendar.HOUR_OF_DAY);
intnowm=now.get(Calendar.MINUTE);
intnows=now.get(Calendar.SECOND);
Stringst;
if(nowh<10)st="0"+nowh;elsest=""+nowh;
if(nowm<10)st+=":0"+nowm;elsest+=":"+nowm;
if(nows<10)st+=":0"+nows;elsest+=":"+nows;
g.setColor(Color.pink);
g.fillRect(L,T,50,28);
g.setColor(Color.blue);
g.drawString(st,L+2,T+26);
ss=90-nows*6;
mm=90-nowm*6;
hh=90-nowh*30-nowm/2;
x0=r+40+L;
y0=r+40+T;
if(olds_x>0){
g.setColor(getBackground());
g.drawLine(x0,y0,olds_x,h-olds_y);
}
else{
old_m=mm;
old_h=hh;
}
x=(int)(r*0.9*Math.cos(RAD*ss))+x0;
y=(int)(r*0.9*Math.sin(RAD*ss))+y0-2*T;
g.setColor(Color.yellow);
g.drawLine(x0,y0,x,h-y);
olds_x=x;
olds_y=y;
g2D.setStroke(newBasicStroke(2.2f));
if(old_m!=mm){
g.setColor(getBackground());
g.drawLine(x0,y0,oldm_x,h-oldm_y);
}
x=(int)(r*0.7*Math.cos(RAD*mm))+x0;
y=(int)(r*0.7*Math.sin(RAD*mm))+y0-2*T;
g.setColor(Color.green);
g.drawLine(x0,y0,x,h-y);
oldm_x=x;
oldm_y=y;
old_m=mm;
g2D.setStroke(newBasicStroke(3.4f));
if(old_h!=hh){
g.setColor(getBackground());
g.drawLine(x0,y0,oldh_x,h-oldh_y);
}
x=(int)(r*0.5*Math.cos(RAD*hh))+x0;
y=(int)(r*0.5*Math.sin(RAD*hh))+y0-2*T;
g.setColor(Color.red);
g.drawLine(x0,y0,x,h-y);
oldh_x=x;
oldh_y=y;
old_h=hh;
}
publicstaticvoidmain(String[]args){
Clockc=newClock();
}}
4
㈧ JAVA畫時鍾代碼
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importsun.util.calendar.Gregorian;
importjava.util.Calendar;
importjava.util.GregorianCalendar;
{
intx,y,x0,y0,r,h,olds_x,olds_y,oldm_x,oldm_y,oldh_x,oldh_y,
ss,mm,hh,old_m,old_h,ang;
finaldoubleRAD=Math.PI/180;
publicClockPointer(){
super("Java時鍾");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Imageimage=getToolkit().getImage("clock.gif");
setIconImage(image);
setSize(400,400);
setBackground(Color.white);
//setLocation(300,150);
this.setLocationRelativeTo(null);
setResizable(true);
intdelay=1000;
//創建一個監聽事件
setVisible(true);
ActionListenerdrawClock=newActionListener(){
publicvoidactionPerformed(ActionEventevt){
repaint();
}
};
//創建一個時間計數器,每一秒觸發一次
newTimer(delay,drawClock).start();
}
java.text.SimpleDateFormatfmTime=newjava.text.SimpleDateFormat("HH:mm:ss");
//繪制圖形
publicvoidpaint(Graphicsg){
super.paint(g);
g.setFont(null);
Graphics2Dg2D=(Graphics2D)g;
Insetsinsets=getInsets();
intL=insets.left/2,T=insets.top/2;
h=getSize().height;
g.setColor(Color.white);
//畫圓
g2D.setStroke(newBasicStroke(2.0f));
g.setColor(Color.gray);
g.drawOval(L+40,T+40,h-80,h-80);
r=h/2-40;
x0=40+r-5+L;
y0=40+r-5-T;
ang=60;
//繪制時鍾上的12個字
for(inti=1;i<=12;i++){
x=(int)((r+10)*Math.cos(RAD*ang)+x0);
y=(int)((r+10)*Math.sin(RAD*ang)+y0);
g.setColor(Color.black);
g.drawString(""+i,x,h-y);
ang-=30;
}
//獲得現在的時間
Calendarnow=newGregorianCalendar();
intnowh=now.get(Calendar.HOUR_OF_DAY);
intnowm=now.get(Calendar.MINUTE);
intnows=now.get(Calendar.SECOND);
Stringst=fmTime.format(now.getTime());
//在窗體上顯示時間
g.setColor(Color.pink);
g.fillRect(L,T,50,28);
g.setColor(Color.blue);
g.drawString(st,L+2,T+26);
//計算時間與度數的關系
ss=90-nows*6;
mm=90-nowm*6;
hh=90-nowh*30-nowm/2;
x0=r+40+L;
y0=r+40+T;
g2D.setStroke(newBasicStroke(1.2f));
//擦除秒針
//if(olds_x>0){
//g.setColor(getBackground());
////g.setColor(Color.gray);
//g.drawLine(x0,y0,olds_x,h-olds_y);//(?)
//}
//繪制秒針
x=(int)(r*0.9*Math.cos(RAD*ss))+x0;
y=(int)(r*0.9*Math.sin(RAD*ss))+y0-2*T;
g.setColor(Color.yellow);
g.drawLine(x0,y0,x,h-y);
olds_x=x;
olds_y=y;
g2D.setStroke(newBasicStroke(2.2f));
//擦除分針
//if(old_m!=mm){
//g.setColor(getBackground());
//g.drawLine(x0,y0,oldm_x,h-oldm_y);
//}
//繪制分針
x=(int)(r*0.7*Math.cos(RAD*mm))+x0;
y=(int)(r*0.7*Math.sin(RAD*mm))+y0-2*T;
g.setColor(Color.green);
g.drawLine(x0,y0,x,h-y);
oldm_x=x;
oldm_y=y;
old_m=mm;
g2D.setStroke(newBasicStroke(3.2f));
//擦除時針
//if(old_h!=hh){
//g.setColor(getBackground());
//g.drawLine(x0,y0,oldh_x,h-oldh_y);
//}
//繪制時針
x=(int)(r*0.5*Math.cos(RAD*hh))+x0;
y=(int)(r*0.5*Math.sin(RAD*hh))+y0-2*T;
g.setColor(Color.red);
g.drawLine(x0,y0,x,h-y);
oldh_x=x;
oldh_y=y;
old_h=hh;
}
publicstaticvoidmain(String[]args){
newClockPointer();
}
}
//整理一下
㈨ JAVA時鍾設計
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* 時鍾程序
*/
public class Clock extends JFrame
{
// 今天的日期對象
private GregorianCalendar now = new GregorianCalendar();
// 時鍾標簽,上面畫的是圓形時鍾
private ClockLabel clockLabel = new ClockLabel();
// 星期標簽,指示星期
private JLabel weekLabel = new JLabel();
// 日期標簽,指示日期
private JLabel dateLabel = new JLabel();
// 品牌標簽
private JLabel remarkLabel = new JLabel();
// 時間標簽,指示時間
private JLabel timeLabel = new JLabel();
public Clock()
{
// 設置主界面屬性
setTitle("時鍾");
setSize(500, 480);
setLocation(100, 100);
init();
setResizable(false);
}
private void init()
{
// 初始化品牌標簽
remarkLabel.setText("MyClock");
remarkLabel.setLocation(225, 80);
remarkLabel.setSize(100, 30);
remarkLabel.setFont(new Font("Bookman Old Style", Font.BOLD, 15));
remarkLabel.setForeground(Color.darkGray);
// 初始化星期標簽
weekLabel.setSize(60, 20);
weekLabel.setLocation(315, 190);
weekLabel.setForeground(Color.darkGray);
weekLabel.setFont(new Font("Arial Narrow", Font.BOLD, 12));
// 為星期標簽賦值
int week = now.get(Calendar.DAY_OF_WEEK);
switch (week)
{
case 1:
weekLabel.setText("SUNDAY");
break;
case 2:
weekLabel.setText("MONDAY");
break;
case 3:
weekLabel.setText("TUESDAY");
break;
case 4:
weekLabel.setText("WEDNESDAY");
break;
case 5:
weekLabel.setText("THURSDAY");
break;
case 6:
weekLabel.setText("FRIDAY");
break;
case 7:
weekLabel.setText("SATURDAY");
break;
}
// 初始化日期標簽
dateLabel.setSize(20, 20);
dateLabel.setLocation(370, 190);
dateLabel.setForeground(Color.darkGray);
dateLabel.setFont(new Font("Fixedsys", Font.BOLD, 12));
// 設置日期標簽的值
dateLabel.setText("" + now.get(Calendar.DATE));
// 初始化時間標簽
timeLabel.setSize(500, 30);
timeLabel.setLocation(100, 400);
timeLabel.setForeground(new Color(0, 64, 128));
timeLabel.setFont(new Font("Fixedsys", Font.PLAIN, 15));
// 將各組件加入到主窗口中
Container con = getContentPane();
con.setBackground(Color.white);
con.setLayout(null);
con.add(weekLabel);
con.add(dateLabel);
con.add(remarkLabel);
con.add(timeLabel);
con.add(clockLabel);
}
public static void main(String[] args)
{
Clock clock = new Clock();
clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clock.setVisible(true);
}
// 自定義時鍾標簽,畫一個圓形的時鍾
class ClockLabel extends JLabel implements Runnable
{
// 時鍾標簽的寬度和高度
private final int WIDTH = 500;
private final int HEIGHT = 440;
// 圓形時鍾的X半徑和Y半徑
private final int CIRCLE_X_RADIUS = 150;
private final int CIRCLE_Y_RADIUS = 155;
// 圓形時鍾的原點
private final int CIRCLE_X = 250;
private final int CIRCLE_Y = 200;
// 圓形時鍾指針的長度
private final int HOUR_LENGTH = 50;
private final int MIN_LENGTH = 80;
private final int SEC_LENGTH = 100;
// 當前時針所處的角度
double arcHour = 0;
// 當前分針所處的角度
double arcMin = 0;
// 當前秒針所處的角度
double arcSec = 0;
// 顏色的透明度,
// 當顏色的alpha值為1或者255時,表示不透明,其他值時透明
int alpha = 50;
// 標識顏色透明度變化的方向,
// 為true時表示越來越透明,為false時表示月來越不透明
boolean flag = false;
// 背景圖片的id,輪換顯示背景圖片時使用
int imageID = 0;
// 背景圖片對象數組
Image img[] = new Image[5];
// 背景圖片URL
URL url[] = new URL[] { ClockLabel.class.getResource("image/1.jpg"), ClockLabel.class.getResource("image/2.jpg"), ClockLabel.class.getResource("image/3.jpg"), ClockLabel.class.getResource("image/4.jpg"), ClockLabel.class.getResource("image/5.jpg"), ClockLabel.class.getResource("image/6.jpg") };
// 一個具有緩沖區的圖像對象
BufferedImage bufferedImage = null;
int imageSize = 2 * Math.max(CIRCLE_X_RADIUS, CIRCLE_Y_RADIUS);
// 為bufferedImage創建的Graphics對象,用於在bufferedImage上畫圖
Graphics bufferedImageGraphics = null;
// 時鍾線程,因為時鍾每秒鍾都要動一次,所以用線程
Thread clockThread = null;
// 構造方法
public ClockLabel()
{
// 設置時鍾標簽的大小
this.setSize(WIDTH, HEIGHT);
// 獲取時針、分針、秒針當前的角度
arcHour = now.get(Calendar.HOUR) * 30; // 一格30度
arcMin = now.get(Calendar.MINUTE) * 6; // 一格6度
arcSec = now.get(Calendar.SECOND) * 6; // 一個6度
// 根據圖片URL創建圖片對象
Toolkit tk = this.getToolkit();
img[0] = tk.createImage(url[0]);
img[1] = tk.createImage(url[1]);
img[2] = tk.createImage(url[2]);
img[3] = tk.createImage(url[3]);
img[4] = tk.createImage(url[4]);
try
{
// 使用MediaTracker載入圖片對象
// MediaTracker 類是一個跟蹤多種媒體對象狀態的實用工具類,
// 媒體對象可以包括音頻剪輯和圖像,但目前僅支持圖像.
MediaTracker mt = new MediaTracker(this);
mt.addImage(img[0], 0);
mt.addImage(img[1], 0);
mt.addImage(img[2], 0);
mt.addImage(img[3], 0);
mt.addImage(img[4], 0);
// 載入媒體跟蹤器中所有的圖像。
mt.waitForAll();
}
catch (Exception e)
{
e.printStackTrace();
}
// 創建一個有緩沖的Image對象
bufferedImage = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
// 為BufferedImage創建Graphics2D對象,
// 以後用該Graphics2D對象畫的圖都會畫在BufferedImage中
bufferedImageGraphics = bufferedImage.createGraphics();
// 啟動線程
clockThread = new Thread(this);
clockThread.start();
}
public void paint(Graphics g1)
{
// Graphics2D繼承Graphics,比Graphics提供更豐富的方法
Graphics2D g = (Graphics2D) g1;
/** ***畫圓形時鍾的刻度,每6度便有一個刻度**** */
for (int i = 0; i < 360; i = i + 6)
{
// 設置畫筆的顏色為藍色
g.setColor(Color.blue);
// 設置畫筆的寬度為2
g.setStroke(new BasicStroke(2));
if (i % 90 == 0)
{
// 對於0,3,6,9點位置,使用一個大的藍色刻度
g.setStroke(new BasicStroke(5));// 畫筆寬度為5
// 當起點和終點一樣時,畫的就是點
g.drawLine(CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS), CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS));
}
else if (i % 30 == 0)
{
// 如果角度處於小時的位置,而且還不在0,3,6,9點時,畫紅色的小刻度
g.setColor(Color.red);
g.drawLine(CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS), CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS));
}
else
{
// 其他位置就畫藍色的小刻度
g.drawLine(CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS), CIRCLE_X + (int) (Math.cos(i * Math.PI / 180) * CIRCLE_X_RADIUS), CIRCLE_Y + (int) (Math.sin(i * Math.PI / 180) * CIRCLE_Y_RADIUS));
}
}
/** ****** 畫時鍾的指針 ******** */
// 畫時針
Line2D.Double lh = new Line2D.Double(CIRCLE_X, CIRCLE_Y, CIRCLE_X + Math.cos((arcHour - 90) * Math.PI / 180) * HOUR_LENGTH, CIRCLE_Y + Math.sin((arcHour - 90) * Math.PI / 180) * HOUR_LENGTH);
// 設置畫筆寬度和顏色
g.setStroke(new BasicStroke(6));
g.setColor(new Color(0, 128, 0));
// 利用Graphics2D的draw方法畫線
g.draw(lh);
// 畫分針
Line2D.Double lm = new Line2D.Double(CIRCLE_X, CIRCLE_Y, CIRCLE_X + Math.cos((arcMin - 90) * Math.PI / 180) * MIN_LENGTH, CIRCLE_Y + Math.sin((arcMin - 90) * Math.PI / 180) * MIN_LENGTH);
g.setStroke(new BasicStroke(3));
g.setColor(new Color(0, 128, 192));
g.draw(lm);
// 畫秒針
Line2D.Double ls = new Line2D.Double(CIRCLE_X, CIRCLE_Y, CIRCLE_X + Math.cos((arcSec - 90) * Math.PI / 180) * SEC_LENGTH, CIRCLE_Y + Math.sin((arcSec - 90) * Math.PI / 180) * SEC_LENGTH);
g.setStroke(new BasicStroke(1));
// 秒針的顏色隨機,使動畫效果明顯。
g.setColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
g.draw(ls);
/** **** 畫時鍾背景,並將其透明處理 ******* */
// 所有使用bufferedImageGraphics畫的圖像,都畫在bufferedImage上,
// drawImage方法的參數含義分別是:背景圖片對象、目標位置第一個角的X、Y坐標、目標位置第二個角的X、Y坐標、
// 源位置第一個角的X、Y坐標、源位置第二個角的X、Y坐標、圖像對象改變時的通知接受者
bufferedImageGraphics.drawImage(img[imageID], 0, 0, imageSize, imageSize, 0, 0, imageSize + 10, imageSize + 10, this);
// 將背景圖片透明化
for (int j = 0; j < imageSize; j++)
{
for (int i = 0; i < imageSize; i++)
{
// 獲得背景圖像中(i, j)坐標的顏色值
int pix = bufferedImage.getRGB(i, j);
Color c = new Color(pix);
int r = c.getRed();
int gr = c.getGreen();
int b = c.getBlue();
// 通過Color對象的alpha,使顏色透明。
int newpix = new Color(r, gr, b, alpha).getRGB();
// 重新設置背景圖像該象素點的顏色
bufferedImage.setRGB(i, j, newpix);
}
}
/** 以上畫背景操作都是畫在bufferedImage上的,這里要將bufferedImage畫在ClockLabel **/
// 將當前用戶剪貼區 Clip 與橢圓區域相交,並將 Clip 設置為所得的交集
g.clip(new Ellipse2D.Double(95, 45, imageSize, imageSize));
g.setColor(Color.white);
// 在用戶剪貼區畫bufferedImage
g.drawImage(bufferedImage, 95, 45, this);
}
public void run()
{
try
{
//
while (clockThread != null)
{
// 獲得完整的日期格式
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
// 格式化當前時間
String s = df.format(new Date());
timeLabel.setText(s);
// 每動一次對時鍾指針的角度進行調整
arcSec += 6;
arcMin += 0.1;
arcHour += 0.1 / 60;
// 當角度滿一圈時,歸0
if (arcSec >= 360)
{
arcSec = 0;
}
if (arcMin >= 360)
{
arcMin = 0;
}
if (arcHour >= 360)
{
arcHour = 0;
}
// 實現背景透明度漸變
// 從淺入深,再由深入淺。
if (flag)
{
alpha += 10;
if (alpha == 50)
{
flag = !flag;
}
}
else
{
alpha -= 10;
if (alpha == 0)
{
flag = !flag;
// 當透明度變化一個輪回時,換一張背景圖
imageID++;
if (imageID == 4)
{
imageID = 0;
}
}
}
// 重畫時鍾標簽
repaint();
// 等待1秒鍾
Thread.sleep(1000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}