📄 clockapplet.java
字号:
package clockapplet;
/**
* Java语言实验参考程序
* Company 北京师范大学计算机系
* @author 孙一林
* @version 1.0
*/
import java.awt.*;
import java.applet.*;
import java.util.Date; // 引入处理时间等内容的包
import java.text.*;
public class ClockApplet extends Applet implements Runnable {
Date timenow; // 声明Date变量
Clock nowClock; // 声明Clock变量
Thread clockthread = null; // 声明一个线程
public void start(){ // 启动线程
if (clockthread == null) {
clockthread = new Thread(this); // 创建新线程
clockthread.start(); // 启动线程
}
}
public void stop() { // 终止线程
clockthread.stop(); // 停止线程
clockthread = null;
}
public void run(){ // 重构run()方法
while(true) { // 循环显示
repaint(); // 刷新界面
try{
Thread.sleep(1000); // 延迟一秒钟
}
catch(InterruptedException e){
}
}
}
public void paint(Graphics g) {
timenow = new Date(); // 获取时、分、秒
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy年MM月dd日 hh:mm:ss a"); // 设置显示的格式
String s_time_msg = sdf.format(timenow);
// s_time_msg中存放格式化后的时间字串
nowClock = new Clock(timenow.getHours(),
timenow.getMinutes(), timenow.getSeconds());
g.drawString(s_time_msg,25,240);
nowClock.show(g,100,100,100);
}
}
class Clock { // 定义处理时间类
int hour,minute,second;
Clock(int hrs,int min,int sec) {
hour = hrs%12;
minute = min;
second = sec;
}
void show(Graphics g,int cx,int cy,int rad) { // 定义show方法
int hrs_len = (int)(rad*0.5); // 时针长度
int min_len = (int)(rad*0.6); // 分针长度
int sec_len = (int)(rad*0.9); // 秒针长度
double theta;
g.drawOval(cx-rad,cy-rad,rad*2,rad*2); // 画钟面
theta=(double)(hour*60*60+minute*60+second)/43200.0*2.0*Math.PI ;
// 画时针
drawNiddle(g,Color.blue,cx,cy,hrs_len,theta); // 画分针
theta=(double)(minute*60+second)/3600.0*2.0*Math.PI ;
drawNiddle(g,Color.red,cx,cy,sec_len,theta); // 画秒针
theta=(double)(second)/60.0*2.0*Math.PI ;
drawNiddle(g,Color.green ,cx,cy,sec_len,theta);
}
private void drawNiddle(
Graphics g,Color c,int x,int y,int len,double theta){
int ex = (int)(x+len*Math.sin(theta));
int ey = (int)(y-len*Math.cos(theta));
g.setColor (c);
g.drawLine(x,y,ex,ey);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -