java 闹钟程序

作者&投稿:帛贝 (若有异议请与网页底部的电邮联系)
急需要一个简单的JAVA闹钟程序~

写了一个,也尽量在你可能不懂的地方添加注释了。不过其实注释越多不见得越好,因为有时你太在意注释反而没弄清整体的代码结构。
import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.Font;import java.awt.Frame;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Timer;import java.util.TimerTask;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineEvent;import javax.sound.sampled.LineListener;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;/** * 闹钟主界面 */public class AlarmClock extends JFrame implements ActionListener {private static final int LOOP_COUNT = 5; // 重复播放的次数private JLabel labelClock, labelAlarm, labelNextAlarm;private JButton btnSet, btnClose;private SetDialog setDialog;private JPanel topPanel, alarmPanel;private Timer timer;private Clip clip;private Calendar alarmCal;private boolean timeReached = true;private DateFormat df = new SimpleDateFormat("HH : mm");public AlarmClock() {super("闹钟");}public void launch() {setSize(400, 300);setVisible(true);setDefaultCloseOperation(EXIT_ON_CLOSE);getContentPane().setLayout(new BorderLayout()); // 利用边界布局将界面分割成上中下三部分labelAlarm = new JLabel("闹钟定时已到!");btnClose = new JButton("确定");labelNextAlarm = new JLabel(); // 指示下一次闹钟时间alarmPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); // 顶部提示栏提示闹钟时间已到,和确定按钮alarmPanel.add(labelAlarm);alarmPanel.add(btnClose);topPanel = new JPanel(new GridLayout(2, 1));topPanel.add(alarmPanel);topPanel.add(labelNextAlarm);alarmPanel.setVisible(false); // 初始隐藏顶部提示栏labelClock = new JLabel();Font font = new Font(Font.SERIF, Font.PLAIN, 48); // 中间的倒计时文本用大号字体展示labelClock.setFont(font);labelClock.setHorizontalAlignment(JLabel.CENTER); // 文本居中btnSet = new JButton("设置");getContentPane().add(topPanel, BorderLayout.NORTH); // 界面顶部getContentPane().add(labelClock, BorderLayout.CENTER); // 界面中部getContentPane().add(btnSet, BorderLayout.SOUTH); // 界面底部btnSet.addActionListener(this); // 设置按钮的点击事件btnClose.addActionListener(this); // 顶部确定按钮的点击事件setLocationRelativeTo(null); // 界面居中setDialog = new SetDialog(this); // 初始化设置对话框try { // 初始化闹钟声音// 目前发现wav格式的文件是可以支持的,mp3不支持AudioInputStream ais = AudioSystem.getAudioInputStream(AlarmClock.class.getResource("/res/alarm.wav"));clip = AudioSystem.getClip();clip.open(ais);ais.close();int loop = LOOP_COUNT = totalFrames) {stopAlarm();}}});} catch (UnsupportedAudioFileException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (LineUnavailableException e) {e.printStackTrace();}initTimer();}public static void main(String[] args) {new AlarmClock().launch(); // 启动主界面}@Overridepublic void actionPerformed(ActionEvent e) {Object source = e.getSource();if(source == btnSet) { // 点击设置按钮时弹出设置界面,以模对话框显示setDialog.setVisible(true);} else if(source == btnClose) { // 点击顶部确定按钮时隐藏顶部提示栏stopAlarm();}}private void initTimer() {timer = new Timer(); // 初始化倒计时任务// 开始倒计时timer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {Calendar cal = Calendar.getInstance();int hour = cal.get(Calendar.HOUR_OF_DAY);int min = cal.get(Calendar.MINUTE);int sec = cal.get(Calendar.SECOND);// 设置倒计时文本labelClock.setText(String.format("%02d : %02d : %02d", hour, min, sec));if(null != alarmCal && !timeReached) {int alarmHour = alarmCal.get(Calendar.HOUR_OF_DAY);int alarmMin = alarmCal.get(Calendar.MINUTE);if(alarmHour == hour && alarmMin == min) { // 到时间时播放声音timeReached = true;System.out.println("Time over");startAlarm();}}}}, 0, 1000L); // 每隔1秒刷新倒计时文本}/** * 开始计时 * @param hour * @param minute */public void startTimer(int hour, int minute) {alarmCal = Calendar.getInstance();alarmCal.set(Calendar.HOUR_OF_DAY, hour);alarmCal.set(Calendar.MINUTE, minute);labelNextAlarm.setText("下次闹钟时间:" + df.format(alarmCal.getTime()));timeReached = false;}/** * 取消倒计时任务 */public void cancelTimer() {labelNextAlarm.setText("");alarmCal = null;}private void startAlarm() { // 开始播放提示音if(null != clip) {alarmPanel.setVisible(true); // 显示顶部提示栏clip.setFramePosition(0); // 将音频帧重置为第0帧clip.loop(LOOP_COUNT); // 开始循环播放}labelNextAlarm.setText("");}private void stopAlarm() { // 停止播放提示音if(null != clip && clip.isRunning()) {clip.stop(); // 结束播放}labelNextAlarm.setText("");alarmPanel.setVisible(false); // 隐藏顶部提示栏}/** * 闹钟设置页面 */class SetDialog extends JDialog implements KeyListener, ActionListener {private JLabel labelHour, labelMin;private JTextField textHour, textMin;private JPanel mainPanel, labelPanel, buttonPanel;private JButton btnOk, btnCancel, btnBack;private Calendar cal = Calendar.getInstance();public SetDialog(Frame frame) {super(frame);setTitle("设置");setModal(true); // 设置为模窗口,就是说在本弹窗未消失时不允许点击主界面。setSize(300, 150);// 显示时分labelHour = new JLabel("时");labelMin = new JLabel("分");labelHour.setHorizontalAlignment(JLabel.CENTER);labelMin.setHorizontalAlignment(JLabel.CENTER);textHour = new JTextField();textMin = new JTextField();// 上面的部分用网格布局将各组件以2x2的格子放进去labelPanel = new JPanel(new GridLayout(2, 2));labelPanel.add(labelHour);labelPanel.add(labelMin);labelPanel.add(textHour);labelPanel.add(textMin);// 时分输入框添加按键监听,只允许输入数字textHour.addKeyListener(this);textMin.addKeyListener(this);// 初始化按钮btnOk = new JButton("确定");btnCancel = new JButton("取消");btnBack = new JButton("返回");// 下面的按钮依次居中放进去buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));buttonPanel.add(btnBack);buttonPanel.add(btnCancel);buttonPanel.add(btnOk);// 初始化主面板,将主面板分割为上下两部分mainPanel = new JPanel(new BorderLayout());mainPanel.add(labelPanel, BorderLayout.CENTER); // 上面显示时分的组件mainPanel.add(buttonPanel, BorderLayout.SOUTH); // 下面排列三个按钮setContentPane(mainPanel);// 设置按钮监听btnBack.addActionListener(this);btnOk.addActionListener(this);btnCancel.addActionListener(this);cal.add(Calendar.HOUR, 1); // 默认设置为当前时间加1小时的整点时间cal.set(Calendar.MINUTE, 0);int hour = cal.get(Calendar.HOUR_OF_DAY);int min = cal.get(Calendar.MINUTE);textHour.setText(String.format("%02d", hour));textMin.setText(String.format("%02d", min));setLocationRelativeTo(frame);}@Overridepublic void keyPressed(KeyEvent arg0) {}@Overridepublic void keyReleased(KeyEvent arg0) {}@Overridepublic void keyTyped(KeyEvent e) {int keyChar = e.getKeyChar(); if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){ }else{ // 如果输入的不是数字则屏蔽输入 e.consume(); //关键,屏蔽掉非法输入 } }@Overridepublic void actionPerformed(ActionEvent e) {Object source = e.getSource();if(source == btnOk) { // 如果点击了确定按钮,则开始计时int hour = 0, min = 0;try {hour = Integer.parseInt(textHour.getText());} catch (NumberFormatException e1) {}try {min = Integer.parseInt(textMin.getText());} catch (NumberFormatException e1) {}startTimer(hour, min);setVisible(false);} else if(source == btnCancel) { // 点击取消按钮时取消计时cancelTimer();setVisible(false);} else if(source == btnBack) { // 点击返回按钮时什么也不做,直接关闭设置界面setVisible(false);}}}}用到的音频文件是wav格式的,你要注意mp3格式的是肯定不行的,其它格式行不行你可以自己试试。wav文件我传到附件上吧,你如果觉得太大的话也可以自己弄一个放到指定目录,记得重命名或修改代码,然后再重新编译运行。

import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;
import java.awt.event.*;

public class Alarm extends Applet implements Runnable
{
Thread timer=null; //创建线程timer
Image gif1; //clockp:闹钟的外壳,闹铃和报时物
boolean setflag=false,stopflag=false,cancelflag=false;
Panel setpanel;
//获取声音文件
AudioClip ring=getAudioClip(getCodeBase(), "1.mid");
Button setbutton=new Button("SET");
Button cancelbutton=new Button("CANCEL");
Button stopbutton=new Button("STOP");
//响应按钮事件
private ActionListener setli=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setflag=true;
}
};
private ActionListener cancelli=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setflag=true;
}
};
private ActionListener stopli=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ring.stop();
//清除的方法
//g.clearRect(83,280,20,30);
}
};


Label note1=new Label("Alarm clock:");
//GregorianCalendar提供的是一个日历式的东东,上面又多了很多的参数,是方便操作了不少。而Date类的功能远不及其,求个和日期有联系的还要自己计算。
GregorianCalendar cal=new GregorianCalendar();
GregorianCalendar cal2=new GregorianCalendar();
SimpleDateFormat df=new SimpleDateFormat("yyyy MM dd HH:mm:ss");//设置时间格式
Date dummy=new Date(); //生成Data对象
String lastdate=df.format(dummy);
Font F=new Font("TimesRoman",Font.PLAIN,14);//设置字体格式
Date dat=null;
Date timeNow;
Color fgcol=Color.blue;
Color fgcol2=Color.darkGray;
Color backcolor=Color.blue;
Label hlabel2,mlabel2,slabel2;//显示时间单位时所用的标签(时、分、秒)
int i;
int s,m,h;
TextField sethour,setmin,setsec;//显示当前时间文本框和定时文本框

//在Applet程序中,首先自动调用初始化完成必要的初始化工作,紧接着自动调用start,在进入执行程序和返回到该页面时被调用,而从该页面转到别的页面时,stop被调用,关闭浏览器时,执行destroy。
public void init()//初始化方法
{
int fieldx=50,fieldy1=120,fieldy2=220,fieldw=30,fieldh=20,space=50;//显示时间和定时文本框的定位参数
setLayout(null); //将布局管理器初始化为null
setpanel=new Panel();
setpanel.setLayout(null);
setpanel.add(note1);
note1.setBounds(30,100,60,20);
note1.setBackground(backcolor);
note1.setForeground(Color.black);
//定时用的文本框(时、分、秒)
sethour=new TextField("00",5);
setmin=new TextField("00",5);
setsec=new TextField("00",5);
hlabel2=new Label();
mlabel2=new Label();
slabel2=new Label();
//定时的小时文本框的位置、大小
setpanel.add(sethour);
sethour.setBounds(fieldx,fieldy2,fieldw,fieldh);
sethour.setBackground(Color.white);
//在文本框后加入单位“时”
setpanel.add(hlabel2);
hlabel2.setText("h");
hlabel2.setBackground(backcolor);
hlabel2.setForeground(Color.black);
hlabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
fieldx=fieldx+space;
//定时的分钟文本框的位置、大小
setpanel.add(setmin);
setmin.setBounds(fieldx,fieldy2,fieldw,fieldh);
setmin.setBackground(Color.white);
//在文本框后加入单位“分”
setpanel.add(mlabel2);
mlabel2.setText("m");
mlabel2.setBackground(backcolor);
mlabel2.setForeground(Color.black);
mlabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
fieldx=fieldx+space;
//定时的秒文本框的位置、大小
setpanel.add(setsec);
setsec.setBounds(fieldx,fieldy2,fieldw,fieldh);
setsec.setBackground(Color.white);
//在文本框后加入单位“秒”
setpanel.add(slabel2);
slabel2.setText("s");
slabel2.setBackground(backcolor);
slabel2.setForeground(Color.black);
slabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
//设置闹钟控制按钮(on,off)
setpanel.add(cancelbutton);
setpanel.add(setbutton);
setpanel.add(stopbutton);
cancelbutton.setBounds(90,180,40,20);
setbutton.setBounds(140,180,40,20);
stopbutton.setBounds(522,180,40,20);
setbutton.addActionListener(setli);
cancelbutton.addActionListener(cancelli);
stopbutton.addActionListener(stopli);
stopbutton.setVisible(false);
//将面板加入当前容器中,并设置面板的大小和背景色
add(setpanel);
setpanel.setBounds(300,1,250,420);
setpanel.setBackground(backcolor);



/*int xcenter,ycenter,s,m,h;
//闹钟中心点所在位置
xcenter=145;
ycenter=162;
s=(int)cal.get(Calendar.SECOND);
m=(int)cal.get(Calendar.MINUTE);
h=(int)cal.get(Calendar.HOUR_OF_DAY);
//初始化指针位置
lastxs=(int)(Math.cos(s*3.14f/30-3.14f/2)*30+xcenter);
lastys=(int)(Math.sin(s*3.14f/30-3.14f/2)*30+ycenter);
lastxm=(int)(Math.cos(m*3.14f/30-3.14f/2)*25+xcenter);
lastym=(int)(Math.sin(m*3.14f/30-3.14f/2)*25+ycenter);
lastxh=(int)(Math.cos((h*30+m/2)*3.14f/180-3.14f/2)*18+xcenter);
lastyh=(int)(Math.sin((h*30+m/2)*3.14f/180-3.14f/2)*18+ycenter);
lasts=s; */

MediaTracker mt=new MediaTracker(this);//为给定组件创建一个跟踪媒体的MediaTracker对象,把图片添加到被跟踪的图片组

//Java允?Sapplet??HTML所在的位置(decument base)下?d?Y料,也允?Sapplet?钠涑淌酱a所在的位置(code base)下?d?Y料。藉由呼叫getDocumentBase()?cgotCodeBase()可得到URL物件。?@些函?????湍阏业侥阆胂螺d的?n案的位置
//clockp=getImage(getDocumentBase(),"11.png");
gif1=getImage(getCodeBase(),"2.gif");

//i为id号

mt.addImage(gif1,i++);

try
{
mt.waitForAll();
}
catch(InterruptedException e)
{};//等待加载结束
resize(600,420);//设置窗口大小
}
//窗口显示有改变的时候调用paint
public void paint(Graphics g)
{//重写paint()方法
int xh,yh,xm,ym,xs,ys,strike_times;
int xcenter,ycenter;
String today;
xcenter=148;
ycenter=186;
dat=new Date();
//用当前时间初始化日历时间
cal.setTime(dat);
//读取当前时间
s=(int)cal.get(Calendar.SECOND);
m=(int)cal.get(Calendar.MINUTE);
h=(int)cal.get(Calendar.HOUR_OF_DAY);
//换一种时间表达形式
today=df.format(dat);
//指针位置
xs=(int)(Math.cos(s*3.14f/30-3.14f/2)*30+xcenter);
ys=(int)(Math.sin(s*3.14f/30-3.14f/2)*30+ycenter);
xm=(int)(Math.cos(m*3.14f/30-3.14f/2)*25+xcenter);
ym=(int)(Math.sin(m*3.14f/30-3.14f/2)*25+ycenter);
xh=(int)(Math.cos((h*30+m/2)*3.14f/180-3.14f/2)*12+xcenter);
yh=(int)(Math.sin((h*30+m/2)*3.14f/180-3.14f/2)*12+ycenter);
//设置字体和颜色
g.setFont(F);
//前景色

g.setColor(getBackground()); //取背景色的
g.drawImage(gif1,75,110,this);
//以数字方式显示年、月、日和时间
g.drawString(today,55,415);

//画指针
g.drawLine(xcenter,ycenter,xs,ys);
g.drawLine(xcenter,ycenter-1,xm,ym); //(x1,y1,x2,y2)
g.drawLine(xcenter-1,ycenter,xm,ym);
g.drawLine(xcenter,ycenter-1,xh,yh);
g.drawLine(xcenter-1,ycenter,xh,yh);



int timedelta;//记录当前时间与闹铃定时的时差
Integer currh,currm,currs;//分别记录当前的时、分、秒


Date dat2=new Date();
cal2.setTime(dat2);
//读取当前时间
currh=(int)cal2.get(Calendar.SECOND);
currm=(int)cal2.get(Calendar.MINUTE);
currs=(int)cal2.get(Calendar.HOUR_OF_DAY);
//这样做的话说我API已过时
//timeNow=new Date();
//currh=new Integer(timeNow.getHours());
//currm=new Integer(timeNow.getMinutes());
//currs=new Integer(timeNow.getSeconds());


if(setflag)
{ //判断是否设置了闹钟
//判断当前时间是否为闹钟所定的时间
if((currh.intValue()==Integer.valueOf(sethour.getText()).intValue())&&(currm.intValue()==Integer.valueOf(setmin.getText()).intValue())&&(currs.intValue()==Integer.valueOf(setsec.getText()).intValue()))
{
ring.play();
g.drawImage(gif1,83,280,this);
stopbutton.setVisible(true);
}
timedelta=currm.intValue()*60+currs.intValue()-Integer.valueOf(setmin.getText()).intValue()*60-Integer.valueOf(setsec.getText()).intValue();
if((timedelta>=30))
{
//若当前时间与闹钟相差时间超过30秒,闹钟自动停
ring.stop();
//清除的方法
g.clearRect(83,280,20,30);
}
}
dat=null;
}

public void start()
{
if(timer==null)
{
timer=new Thread(this);//将timer实例化
timer.start();
}
}



public void stop()
{
timer=null;
}

//给创建线程后start之后自动执行的函数
public void run()
{
//在run()方法中,调用repaint()方法,以重绘小程序区,进行时钟显示的更新。接着调用sleep方法让当前线程(也就是我们创建的线程clockthread)睡眠1000毫秒,因为我们每秒钟要更新一下显示,所以让它睡眠1秒
while(timer!=null)
{
try
{
timer.sleep(1000);
}
catch(InterruptedException e)
{}
//调用repaint时,会首先清除掉paint方法之前的画的内容,再调用paint方法
repaint();//刷新画面
}
timer=null;
}


//当AWT接收到一个applet的重绘请求时,它就调用applet的 update(),默认地,update() 清除applet的背景,然后调用 paint()。重载 update(),将以前在paint()中的绘图代码包含在update()中,从而避免每次重绘时将整个区域清除
//有两种方法可以明显地减弱闪烁:重载 update()或使用双缓冲。
//使用双缓冲技术:另一种减小帧之间闪烁的方法是使用双缓冲,它在许多动画Applet中被使用。其主要原理是创建一个后台图像,将需要绘制的一帧画入图像,然后调用DrawImage()将整个图像一次画到屏幕上去;好处是大部分绘制是离屏的,将离屏图像一次绘至屏幕上比直接在屏幕上绘制要有效得多,大大提高做图的性能。
// 双缓冲可以使动画平滑,但有一个缺点,要分配一张后台图像,如果图像相当大,这将需要很大一块内存;当你使用双缓冲技术时,应重载 update()。

public void update(Graphics g)
{
Image offscreen_buf=null;
//采用双缓冲技术的update()方法
if(offscreen_buf==null)
offscreen_buf=createImage(600,420);
Graphics offg=offscreen_buf.getGraphics();
offg.clipRect(1,1,599,419);
paint(offg);
Graphics ong=getGraphics();
ong.clipRect(1,1,599,419);
ong.drawImage(offscreen_buf,0,0,this);
}







/** Creates a new instance of AlarmClock */
}

import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;

public class AlarmClock extends Applet implements Runnable
{
Thread timer=null; //创建线程timer
Image clockp,gif1,gif2,clock6,clock7; //clockp:闹钟的外壳,闹铃和报时鸟
int s,m,h,hh;
AudioClip ipAu,danger,chirp;
boolean canPaint=true;
boolean flag=false;
boolean strike=true;
int counter=0;
int lasts;
Image offscreen_buf=null;
int i,j,t=0;
int timeout=166;
int lastxs=0,lastys=0,lastxm=0,lastym=0,lastxh=0,lastyh=0;
Date dummy=new Date(); //生成Data对象
GregorianCalendar cal=new GregorianCalendar();
SimpleDateFormat df=new SimpleDateFormat("yyyy MM dd HH:mm:ss");//设置时间格式
String lastdate=df.format(dummy);
Font F=new Font("TimesRoman",Font.PLAIN,14);//设置字体格式
Date dat=null;
Date timeNow=null;
Color fgcol=Color.blue;
Color fgcol2=Color.darkGray;

Panel setpanel;
Color backcolor=Color.pink;
TextField showhour,showmin,showsec,sethour,setmin,setsec;//显示当前时间文本框和定时文本框
Button onbutton;
Button offbutton;
Label hlabel1,mlabel1,slabel1,hlabel2,mlabel2,slabel2;//显示时间单位时所用的标签(时、分、秒)
Label info1=new Label("欢迎使用定时提醒闹钟"),info2=new Label("");
Label note1=new Label("当前时间:"),note2=new Label("闹钟设置:");
boolean setalerm=false,clickflag=false;//判断是否响铃和振动
int fixh=0,fixm=0,fixs=0;//记录闹钟的定时

public void init()//初始化方法
{
Integer gif_number;
int fieldx=50,fieldy1=120,fieldy2=220,fieldw=30,fieldh=20,space=50;//显示时间和定时文本框的定位参数

setLayout(null); //将布局管理器初始化为null
setpanel=new Panel();
setpanel.setLayout(null);
setpanel.add(note1);
setpanel.add(note2);
note1.setBounds(30,100,60,20);
note1.setBackground(backcolor);
note1.setForeground(Color.black);
note2.setBounds(30,180,60,20);
note2.setBackground(backcolor);
note2.setForeground(Color.black);

hlabel1=new Label();
mlabel1=new Label();
slabel1=new Label();
hlabel2=new Label();
mlabel2=new Label();
slabel2=new Label();
//显示当前时间用的文本框
showhour=new TextField("00",5);
showmin=new TextField("00",5);
showsec=new TextField("00",5);
//定时用的文本框(时、分、秒)
sethour=new TextField("00",5);
setmin=new TextField("00",5);
setsec=new TextField("00",5);
//当前时间用的文本框的位置、大小
setpanel.add(showhour);
showhour.setBounds(fieldx,fieldy1,fieldw,fieldh);
showhour.setBackground(Color.white);
//在文本框后加入单位“时”
setpanel.add(hlabel1);
hlabel1.setText("时");
hlabel1.setBackground(backcolor);
hlabel1.setForeground(Color.black);
hlabel1.setBounds(fieldx+fieldw+3,fieldy1,14,20);
fieldx=fieldx+space;
//当前时间的分钟文本框的位置、大小
setpanel.add(showmin);
showmin.setBounds(fieldx,fieldy1,fieldw,fieldh);
showmin.setBackground(Color.white);
//在文本框后加入单位“分”
setpanel.add(mlabel1);
mlabel1.setText("分");
mlabel1.setBackground(backcolor);
mlabel1.setForeground(Color.black);
mlabel1.setBounds(fieldx+fieldw+3,fieldy1,14,20);
fieldx=fieldx+space;
//当前时间的秒文本框的位置、大小
setpanel.add(showsec);
showsec.setBounds(fieldx,fieldy1,fieldw,fieldh);
showsec.setBackground(Color.white);
//在文本框后加入单位“秒”
setpanel.add(slabel1);
slabel1.setText("秒");
slabel1.setBackground(backcolor);
slabel1.setForeground(Color.black);
slabel1.setBounds(fieldx+fieldw+3,fieldy1,14,20);
fieldx=50;
//定时的小时文本框的位置、大小
setpanel.add(sethour);
sethour.setBounds(fieldx,fieldy2,fieldw,fieldh);
sethour.setBackground(Color.white);
//在文本框后加入单位“时”
setpanel.add(hlabel2);
hlabel2.setText("时");
hlabel2.setBackground(backcolor);
hlabel2.setForeground(Color.black);
hlabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
fieldx=fieldx+space;
//定时的分钟文本框的位置、大小
setpanel.add(setmin);
setmin.setBounds(fieldx,fieldy2,fieldw,fieldh);
setmin.setBackground(Color.white);
//在文本框后加入单位“分”
setpanel.add(mlabel2);
mlabel2.setText("分");
mlabel2.setBackground(backcolor);
mlabel2.setForeground(Color.black);
mlabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
fieldx=fieldx+space;
//定时的秒文本框的位置、大小
setpanel.add(setsec);
setsec.setBounds(fieldx,fieldy2,fieldw,fieldh);
setsec.setBackground(Color.white);
//在文本框后加入单位“秒”
setpanel.add(slabel2);
slabel2.setText("秒");
slabel2.setBackground(backcolor);
slabel2.setForeground(Color.black);
slabel2.setBounds(fieldx+fieldw+3,fieldy2,14,20);
//设置闹钟控制按钮(on,off)
onbutton=new Button("开");
offbutton=new Button("关");
setpanel.add(onbutton);
setpanel.add(offbutton);
onbutton.setBounds(90,180,40,20);
offbutton.setBounds(140,180,40,20);
//加入一些附加的信息标签(题头,题尾)
setpanel.add(info1);
info1.setBackground(backcolor);
info1.setForeground(Color.blue);
info1.setBounds(50,50,150,20);
setpanel.add(info2);
info2.setBackground(backcolor);

info2.setForeground(Color.blue);
info2.setBounds(150,280,100,20);
//将面板加入当前容器中,并设置面板的大小和背景色
add(setpanel);
setpanel.setBounds(300,1,250,420);
setpanel.setBackground(backcolor);
//获取声音文件
ipAu=getAudioClip(getDocumentBase(),"bells/仙剑.mid");
danger=getAudioClip(getDocumentBase(),"bells/0.mid");
chirp=getAudioClip(getDocumentBase(),"bells/3.mid");

int xcenter,ycenter,s,m,h;
xcenter=145;
ycenter=162;
s=(int)cal.get(Calendar.SECOND);
m=(int)cal.get(Calendar.MINUTE);
h=(int)cal.get(Calendar.HOUR_OF_DAY);
//初始化指针位置
lastxs=(int)(Math.cos(s*3.14f/30-3.14f/2)*30+xcenter);
lastys=(int)(Math.sin(s*3.14f/30-3.14f/2)*30+ycenter);
lastxm=(int)(Math.cos(m*3.14f/30-3.14f/2)*25+xcenter);
lastym=(int)(Math.sin(m*3.14f/30-3.14f/2)*25+ycenter);
lastxh=(int)(Math.cos((h*30+m/2)*3.14f/180-3.14f/2)*18+xcenter);
lastyh=(int)(Math.sin((h*30+m/2)*3.14f/180-3.14f/2)*18+ycenter);
lasts=s;

MediaTracker mt=new MediaTracker(this);//创建Tracke对象
clockp=getImage(getDocumentBase(),"休闲.png");
gif1=getImage(getDocumentBase(),"gif1.gif");
gif2=getImage(getDocumentBase(),"gif2.gif");
clock6=getImage(getDocumentBase(),"clock6.gif");
clock7=getImage(getDocumentBase(),"clock7.gif");
mt.addImage(clockp,i++);
mt.addImage(gif1,i++);
mt.addImage(gif2,i++);
mt.addImage(clock6,i++);
mt.addImage(clock7,i++);
try{mt.waitForAll();}catch(InterruptedException e){};//等待加载结束
resize(600,420);//设置窗口大小
}

public void paint(Graphics g){//重写paint()方法
int xh,yh,xm,ym,xs,ys,strike_times;
int xcenter,ycenter;
String today;
Integer gif_number;
xcenter=148;
ycenter=186;
dat=new Date();
cal.setTime(dat);
//读取当前时间
s=(int)cal.get(Calendar.SECOND);
m=(int)cal.get(Calendar.MINUTE);
h=(int)cal.get(Calendar.HOUR_OF_DAY);
today=df.format(dat);
//指针位置
xs=(int)(Math.cos(s*3.14f/30-3.14f/2)*30+xcenter);
ys=(int)(Math.sin(s*3.14f/30-3.14f/2)*30+ycenter);
xm=(int)(Math.cos(m*3.14f/30-3.14f/2)*25+xcenter);
ym=(int)(Math.sin(m*3.14f/30-3.14f/2)*25+ycenter);
xh=(int)(Math.cos((h*30+m/2)*3.14f/180-3.14f/2)*18+xcenter);
yh=(int)(Math.sin((h*30+m/2)*3.14f/180-3.14f/2)*18+ycenter);
//设置字体和颜色
g.setFont(F);
g.setColor(fgcol);
g.setColor(fgcol2);
g.setColor(getBackground());
g.fillRect(1,1,634,419);
g.drawImage(clockp,75,110,this);
g.drawImage(clock6,83,280,this);
g.setColor(fgcol2);
g.setColor(getBackground());
g.setColor(fgcol2);
//以数字方式显示年、月、日和时间
g.drawString(today,55,415);
g.drawLine(xcenter,ycenter,xs,ys);
g.setColor(fgcol);
//画指针
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);
lastxs=xs;lastys=ys;
lastxm=xh;lastym=ym;
lastxh=xh;lastyh=yh;
lastdate=today;

if(h<12)hh=h;//将系统时间变换到0-11区间
else hh=h-12;
if(hh==0) strike_times=12;//计算整点时钟声数
else strike_times=hh;
if((s==0&&m==0)||flag){//判断是否整点,是否是主动刷新
if(counter<strike_times){
flag=true;
g.drawImage(gif2,115,35,this);
if(lasts!=s){
if(strike){
counter++;
danger.play();//播放闹铃声
}
if(strike)strike=false;
else strike=true;
}
}
else {
counter=0;
flag=false;
}
}
else
g.drawImage(gif1,115,35,this);

int timedelta;//记录当前时间与闹铃定时的时差
Integer currh,currm,currs;//分别记录当前的时、分、秒

timeNow=new Date();
currh=new Integer(timeNow.getHours());
currm=new Integer(timeNow.getMinutes());
currs=new Integer(timeNow.getSeconds());
//判断是否要更新当前显示的时间,这样可以避免文本框出现频率闪动
if(currh.intValue()!=Integer.valueOf(showhour.getText()).intValue())
showhour.setText(currh.toString());
if(currm.intValue()!=Integer.valueOf(showmin.getText()).intValue())
showmin.setText(currh.toString());
if(currs.intValue()!=Integer.valueOf(showsec.getText()).intValue())
showsec.setText(currh.toString());

if(setalerm){ //判断是否设置了闹钟
//判断当前时间是否为闹钟所定的时间
if((currh.intValue()==fixh)&&(currm.intValue()==fixm)&&(currs.intValue()==fixs))
clickflag=true;
timedelta=currm.intValue()*60+currs.intValue()-fixm*60-fixs;
if((timedelta<60)&&(clickflag==true)){ //若当前时间与闹钟相差时间达到60秒
chirp.play();
g.drawImage(clock7,83,280,this);
}
else{
chirp.stop();
clickflag=false;
}
}
if(lasts!=s)
ipAu.play();//播放滴答声
lasts=s;
if(canPaint){
t+=1;
if(t==12)t=0;
}
canPaint=false;
dat=null;
}
public void start(){
if(timer==null){
timer=new Thread(this);//将timer实例化
timer.start();
}
}
public void stop(){
timer=null;
}
public void run(){
while(timer!=null){
try{timer.sleep(timeout);}catch(InterruptedException e){}
canPaint=true;
repaint();//刷新画面
}
timer=null;
}

public void update(Graphics g){ //采用双缓冲技术的update()方法
if(offscreen_buf==null)
offscreen_buf=createImage(600,420);
Graphics offg=offscreen_buf.getGraphics();
offg.clipRect(1,1,599,419);
paint(offg);
Graphics ong=getGraphics();
ong.clipRect(1,1,599,419);
ong.drawImage(offscreen_buf,0,0,this);
}

public boolean action(Event evt,Object arg){ //按钮事件处理函数
if(evt.target instanceof Button){
String lable=(String)arg;
if(lable.equals("开")){
setalerm=true;
//获取输入的时间
fixh=Integer.valueOf(sethour.getText()).intValue();
fixm=Integer.valueOf(setmin.getText()).intValue();
fixs=Integer.valueOf(setsec.getText()).intValue();

clickflag=false;
}
if(lable.equals("关")){
setalerm=false;
if(chirp!=null)
chirp.stop();
clickflag=false;
}
return true;
}
return false;
}
}


四方台区18176882572: 用JAVA编一个小闹钟 -
后殃康得: import java.awt.*;

四方台区18176882572: 有没有JAVA闹钟的小程序啊~不要太复杂,越简单越好啊~分大大的加啦!急!!!!!!!!!!!! -
后殃康得: 这个是我能想到的除了系统任务之外,最简单最节省系统资源的了 import java.io.File; import java.util.Calendar; import java.util.Date; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Alert { public static void main(String args...

四方台区18176882572: JAVA电子闹钟 -
后殃康得: 这个功能很简单的啦,可以使用timer类来实现,去看看timer吧,很方便的

四方台区18176882572: 求一个 java 多线程闹钟的例子,就是可以同时设置多个不同时段的闹钟 -
后殃康得: public class ThreadPoolManager { private static ThreadPoolManager instance = null; private List<Upload> taskQueue = Collections.synchronizedList(new LinkedList<Upload>());//任务队列 private WorkThread[] workQueue ; //工作线程(真正执...

四方台区18176882572: 寻找java编程高手写一个闹钟的程序 -
后殃康得: 自己之前做过的一个:

四方台区18176882572: 诚心求java程序 -
后殃康得: 设置闹钟:(用三个全局变量带实现,h,m,s)var h = 14;var m = 30;var s = 30; //14:30:30结束闹钟:将全局变量清空.修改闹钟:修改全局变量.闹钟弹出框代码:var nowtime = new Date();var nowh = nowtime.getHours();var nowm = nowtime.getMinutes();var nows = nowtime.getSeconds();if(nowh == h && nowm == m && nows == s){alert("时间到!");}(可以加上日期的设置变量.这种方式不一定是你要的方式,希望可以给你启发)

四方台区18176882572: 怎样用java 程序写一个时钟程序 -
后殃康得: 面向对象思想写成:下面是一个显示器类 public class Display { private int value;//现在的值 private int limit;//上限值 Display( int limit) { this.limit = limit; } public void increase() { value++; if(value == limit) { value = 0; } } public int getValue() { return ...

四方台区18176882572: JAVA 闹钟程序 -
后殃康得: //OK 写好了...怕你不懂 帮你加了注释 package 娱乐; import java.applet.Applet; import java.applet.AudioClip; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import ...

四方台区18176882572: 用Java写一个闹钟 每天早上6点30响 怎么做 -
后殃康得: z自己写一个贝 用线程控制你要定时的时间 呵呵应该不难的呀 建议自己写 如果有什么地方写不出来了 大家一起来解决 这样才是编程指导

四方台区18176882572: 有哪位大神知道用java写闹钟程序怎么计算闹钟时间与当前时间差么,拜托了 -
后殃康得: SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date nowdate = new Date();//系统当前时间 java.util.Date begin=dfs.parse("2015-12-25 12:30:00");//闹钟设置时间可以获取,我暂时写死 java.util.Date end = ...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网