5B2、如下图所示,利用Java的GUI和多线程编程技术,编写一个时钟显示程序。(30分)
http://s14/mw690/64ecfc2fgd08d6ef6619d&690例题 利用Java的GUI和多线程编程技术,编写一个时钟显示程序(第五届ITAT jav" TITLE="JAVA深入 例题 利用Java的GUI和多线程编程技术,编写一个时钟显示程序(第五届ITAT jav" />
public class ThreadClock extends JFrame implements Runnable{
private volatileBufferedImage boardDrawing;//volatile是程度较轻的 synchronized
private volatileBufferedImage boardDisplaying;
publicThreadClock()
{
setTitle("ThreadClock");
setSize(300, 300);
setLocation(450,200);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
boardDrawing = newBufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
boardDisplaying = newBufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
}
public voidpaint(Graphics g) {
g.drawImage(boardDisplaying, 0, 0, null);
}
@Override
public void
run() {
//本来我这里的循环条件为true,不过测试运行了几次之后发现这个线程并没有被关闭
//内存使用变成了3GB+,任务管理器中满是javaw.exe
//后来用this.isShowing()来判断一下,终于可以顺利结束进程了
while(this.isShowing())
{
Graphics g = boardDrawing.getGraphics();
g.setColor(Color.WHITE);
g.clearRect(0, 0, boardDrawing.getWidth(), boardDrawing.getHeight());//清除图形
g.fillRect(0, 0, boardDrawing.getWidth(), boardDrawing.getHeight());//填充背景色为白色
//画图
//画出clock的表盘及数字
g.setColor(Color.BLUE);
g.drawOval(100, 100, 100, 100);
g.drawString("12", 145,
115);
g.drawString("6", 145,
195);
g.drawString("9", 105,
155);
g.drawString("3", 190,
155);
//get Instance Time得到当前时间
Calendar c=Calendar.getInstance();
intweek=c.get(Calendar.DAY_OF_WEEK);
intmonth=c.get(Calendar.MONTH);
intday=c.get(Calendar.DATE);
inthour=c.get(Calendar.HOUR_OF_DAY);
intminute=c.get(Calendar.MINUTE);
intsecond=c.get(Calendar.SECOND);
int year=c.get(Calendar.YEAR);
//画出时针分针秒针
DrawHands(g, second/60.0, 40);
DrawHands(g, minute/60.0, 32);
DrawHands(g, (hour)/12.0, 25);
String[] weekName={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
String[] monthName={"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
//画出显示时间的字符串
String timeString=String.format("%s %s -
-:-:- %s",
weekName[week],monthName[month],day,hour,minute,second,year);
g.drawString(timeString, 75, 215);
g.drawString("neolone", 240,
280);
// 切换前景与背景工作区
BufferedImage tmp = boardDisplaying;
boardDisplaying = boardDrawing;
boardDrawing = tmp;
this.repaint();
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
}
}
//用g画出某根针(时分秒只是长度不同),percent表示从十二点到某指针现在的位置占整个圆周的百分比,length表示长度
private voidDrawHands(Graphics g,Double percent,int length)
{
doubledegree=360*percent;
int x=(int)(150+Math.cos(2*Math.PI*(90-degree)/360)*length);
int y=(int)(150-Math.sin(2*Math.PI*(90-degree)/360)*length);
g.drawLine(150, 150, x, y);
}
public static voidmain(String[] args) {
// TODOAuto-generated
method stub
ThreadClock clock=newThreadClock();
newThread(clock).start();
}
}
加载中,请稍候......