導航:首頁 > 編程語言 > java小鬧鍾詳細教程

java小鬧鍾詳細教程

發布時間:2021-03-04 03:50:26

㈠ 尋找java編程高手寫一個鬧鍾的程序

自己之前做過的一個:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class Clock extends JFrame implements ActionListener {
public final int HEIGTH = 200, L0 = 50, T0 = 50,N=8;
public final double RAD = Math.PI / 180.0;
int x, y, old_X, old_Y, r, x0, y0, w, h, ang;
int sdo, mdo, hdo, old_M, old_H, hh, mm, ss;
int delay = 1000;
Calendar now;
String st, alarm, Items1, Items2,str[];
JButton jb;
JComboBox jc1, jc2, jc3;
JLabel jl1, jl2, jl3, jl4;
JMenu jm1, jm2, jm3, jm4;
JMenuBar jmb;
JMenuItem jmi1, jmi2, jmi3, jmi4, jmi5, jmi6, jmi7, jmi8, jmi9,jmi10;
JTextField jtf1, jtf2, time;
JPanel jp1, jp2, jp3;
Timer timer;
TimeZone tz = TimeZone.getTimeZone("JST");
Toolkit toolkit=Toolkit.getDefaultToolkit();;
/**
* <br>
* 方法說明:實現類必須過載的方法
*/

public static void main(String[] args) {
Clock cp = new Clock();
cp.setVisible(true);
}

Clock() {
super("Java鬧鍾!");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(550, 700);
setVisible(true);
Container contentPane = getContentPane();

jp2 = new JPanel();

jmb = new JMenuBar();

jm1 = new JMenu("背景顏色設置 ", true);
jmi1 = new JMenuItem("外圈顏色");
jmi1.addActionListener(this);
jmi1.setActionCommand("color1");
jm1.add(jmi1);
jmi2 = new JMenuItem("鬧鍾邊線顏色");
jmi2.addActionListener(this);
jmi2.setActionCommand("color2");
jm1.add(jmi2);
jmi3=new JMenuItem("底盤顏色");
jmi3.addActionListener(this);
jmi3.setActionCommand("color3");
jm1.add(jmi3);
jmi4=new JMenuItem("系統時間背靜顏色");
jmi4.addActionListener(this);
jmi4.setActionCommand("color4");
jm1.add(jmi4);
jmb.add(jm1);

jm2 = new JMenu("指針顏色設置 ", true);
jmi5 = new JMenuItem("秒針顏色");
jmi5.addActionListener(this);
jmi5.setActionCommand("color5");
jm2.add(jmi5);
jmi6 = new JMenuItem("分針顏色");
jmi6.addActionListener(this);
jmi6.setActionCommand("color6");
jm2.add(jmi6);
jmi7 = new JMenuItem("時針顏色");
jmi7.addActionListener(this);
jmi7.setActionCommand("color7");
jm2.add(jmi7);
jmb.add(jm2);

jm3 = new JMenu("鬧鈴聲音設置 ", true);
jmi8 = new JMenuItem("響鈴1");
jmi8.addActionListener(this);
jmi8.setActionCommand("ring1");
jm3.add(jmi8);
jmi9 = new JMenuItem("靜音");
jmi9.addActionListener(this);
jmi9.setActionCommand("ring2");
jm3.add(jmi9);
jmb.add(jm3);

jm4 = new JMenu("幫助 ", true);
jmi10=new JMenuItem("使用說明");
jmi10.addActionListener(this);
jmi10.setActionCommand("help");
jm4.add(jmi10);
jmb.add(jm4);
jp2.add(jmb);

contentPane.add(jp2, BorderLayout.NORTH);

jp3 = new JPanel();
jl1 = new JLabel("鬧鈴時間");
jl1.setFont(new Font("楷體_GB2312", Font.BOLD, 18));
time = new JTextField("00:00", 5);
alarm = time.getText();
jb = new JButton("修改鬧鈴時間");
jb.addActionListener(this);
jb.setActionCommand("CC");
jp3.add(jl1);
jp3.add(time);
jp3.add(jb);
contentPane.add(jp3, BorderLayout.SOUTH);

ClockPanel clock = new ClockPanel();
contentPane.add(clock, BorderLayout.CENTER);

// 窗體添加事件監聽,監聽秒錶的觸發
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
repaint();
}
};
new Timer(delay, taskPerformer).start();
}

/**
* <br>
* 方法說明:繪制圖形
*/

Color C1 = Color.lightGray;// 外圈顏色
Color C2 = Color.black;// 邊線顏色
Color C3 = Color.magenta;// 內盤顏色
Color C4 = Color.blue;// 背景顏色
Color C5 = Color.yellow;// 秒針顏色
Color C6 = Color.green;// 分針顏色
Color C7 = Color.red;//時針顏色
public class ClockPanel extends JPanel {
public void paint(Graphics g) {
h = getSize().height - 200;
// 繪制圓形
g.setColor(C1);
g.fillOval(L0 + 30, T0 + 30, h - 60, h - 60);
g.setColor(C2);
g.drawOval(L0 + 31, T0 + 31, h - 62, h - 62);
g.setColor(C3);
g.fillOval(L0 + 50, T0 + 50, h - 100, h - 100);
g.setColor(C2);
g.drawOval(L0 + 51, T0 + 51, h - 102, h - 102);

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;
g.drawString("指針式時鍾", 215, 200);

// 獲取時間
now = Calendar.getInstance();
hh = now.get(Calendar.HOUR_OF_DAY);// 小時
mm = now.get(Calendar.MINUTE);// 分鍾
ss = now.get(Calendar.SECOND);// 秒
g.setColor(C4);
g.fillRect(5, 550, 150, 30);// 填充的矩形
g.setColor(C6);
if (hh < 10)
st = "0" + hh;
else
st = "" + hh;
if (mm < 10)
st = st + ":0" + mm;
else
st = st + ":" + mm;
if(alarm.equals(st))
{
if(toolkit!=null)
toolkit.beep();
else {}
}
if (ss < 10)
st = st + ":0" + ss;
else
st = st + ":" + ss;
{
g.setFont(new Font("華文楷體", Font.BOLD, 16));
g.drawString("系統時間:" + st, 10, 570);
}

// 計算時間和圖形的關系
sdo = 90 - ss * 6;
mdo = 90 - mm * 6;
hdo = 90 - hh * 30 - mm / 2;
// 擦除秒針
if (old_X > 0) {
g.setColor(C3);
} else {
old_M = mdo;
old_H = hdo;
}
// 繪制秒針
g.setColor(C5);
x = (int) ((r - 26) * Math.cos(RAD * sdo) + x0);
y = (int) ((r - 26) * Math.sin(RAD * sdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));

old_X = x;
old_Y = y;

// 擦除分針和時針
if (mdo != old_M) {
g.setColor(C3);
old_M = mdo;
}
if (hdo != old_H) {
g.setColor(C3);
old_H = hdo;
}
// 繪制分針
g.setColor(C6);
x = (int) ((r - 50) * Math.cos(RAD * mdo) + x0);
y = (int) ((r - 50) * Math.sin(RAD * mdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));
// 繪制時針
g.setColor(C7);
x = (int) ((r - 90) * Math.cos(RAD * hdo) + x0);
y = (int) ((r - 90) * Math.sin(RAD * hdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));
} // end paint
}

// 鬧鈴時間的判斷及實現
// 鬧鈴聲音的實現

public void actionPerformed(ActionEvent e) {
// JMenuItem m = (JMenuItem) e.getSource();

if (e.getActionCommand() == "CC") {
int newHou, newMin;
char c;

String getTime = JOptionPane.showInputDialog(this, "請輸入鬧鈴時間格式如:", "00:00");
repaint();

//如果撤消設置時間,就什麼列印null
if(getTime==null)
System.out.println(getTime);
// dispose();

judge: if (getTime != null) {
//列印輸入的設置的時間
System.out.println(getTime);
// 判斷輸入的是不是5位字元
if (getTime.length() != 5) {
JOptionPane.showMessageDialog(time, "格式錯誤\n請按格式輸入5位數字", "Error",
JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}

// 判斷輸入的是不是數字
for (int i = 0; i < (getTime.length()); i++) {
c = getTime.charAt(i);
if (i == 2 && !Character.isDigit(c))
continue;
// 判斷當前字元,如果不是數字則跳出該事件
if (i != 2 && !Character.isDigit(c)) {
JOptionPane.showMessageDialog(this, "格式錯誤\n請按格式輸入5位數字",
"Error",JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
}
char[] hour = { getTime.charAt(0), getTime.charAt(1) };
char[] minute = { getTime.charAt(3), getTime.charAt(4) };
newHou = Integer.parseInt(String.valueOf(hour));
newMin = Integer.parseInt(String.valueOf(minute));
if (newHou >= 24 || newHou < 0) {
JOptionPane.showMessageDialog(this, "格式錯誤\n小時應該是不小於0不大於23的正數",
"Error", JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
if (newMin >= 60 || newHou < 0) {
JOptionPane.showMessageDialog(this, "格式錯誤\n分鍾應該是小於60的正數", "Error",
JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
new SetTime(newHou, newMin);
}
}

if (e.getActionCommand() == "ring1") {
toolkit=Toolkit.getDefaultToolkit();
}
if(e.getActionCommand() == "ring2"){
System.out.println("靜音");
toolkit=null;

}

if (e.getActionCommand() == "color1") {
String color;
Color c;
System.out.println("color1");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的外圈顏色(0--255)", "128");
if (color == null) {
} else {
if (Integer.parseInt(color) < 0
|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的外圈顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C1 = c;
}
}
}
if(e.getActionCommand() == "color2"){
String color;
Color c;
System.out.println("color2");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的邊線顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的邊線顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C2 = c;
}
}
}
if(e.getActionCommand() == "color3"){
String color;
Color c;
System.out.println("color3");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的內盤顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的內盤顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C3 = c;
}
}
}

if(e.getActionCommand() == "color4"){
String color;
Color c;
System.out.println("color4");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的背景顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的背景顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C4 = c;
}
}
}
if(e.getActionCommand() == "color5"){
String color;
Color c;
System.out.println("color5");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的秒針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的秒針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C5 = c;
}
}
}
if(e.getActionCommand() == "color6"){
String color;
Color c;
System.out.println("color6");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的分針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的分針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C6 = c;
}
}
}

if(e.getActionCommand() == "color7"){
String color;
Color c;
System.out.println("color7");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的時針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的時針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C7 = c;
}
}
}

if(e.getActionCommand() == "help"){
String help;
help = JOptionPane.showInputDialog(this, "輸入quit退出該鬧鍾的使用", "這是運行在Java中的指針式時鍾");
if(help.equals("quit"))
dispose();
else {}
// timer.restart();
}
}

class SetTime {
String Hour;
String Minute;

public SetTime() { }
public SetTime(int hour, int minute) {
// 當時間參數小於10的時候在前面添加字元0
if (hour < 10) {
Hour = "0" + String.valueOf(hour);
} else {
Hour = "" + String.valueOf(hour);
}
if (minute < 10) {
Minute = "0" + String.valueOf(minute);
} else {
Minute = "" + String.valueOf(minute);
}
alarm = Hour + ":" + Minute;
time.setText(alarm);
repaint();
}
}
}

㈡ 怎樣用java製作一個鍾表類

public class Horologe{
private int hour;
private int minute;
private int second;
public void setTime(int hour,int minute,int second){ //設置時間的方法
this.hour = hour; //傳進的參數賦值給成員變數
this.minute = minute;
this.second = second;
}
public String showTime(){ //顯示時間的方法
return "小時內:"+hour+" 分鍾:"+minute+" 秒: "+second;
}
}
希望能夠幫到你容

㈢ 用JAVA編一個小鬧鍾

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class Clock extends JFrame implements ActionListener {
public final int HEIGTH = 200, L0 = 50, T0 = 50,N=8;
public final double RAD = Math.PI / 180.0;
int x, y, old_X, old_Y, r, x0, y0, w, h, ang;
int sdo, mdo, hdo, old_M, old_H, hh, mm, ss;
int delay = 1000;
Calendar now;
String st, alarm, Items1, Items2,str[];
JButton jb;
JComboBox jc1, jc2, jc3;
JLabel jl1, jl2, jl3, jl4;
JMenu jm1, jm2, jm3, jm4;
JMenuBar jmb;
JMenuItem jmi1, jmi2, jmi3, jmi4, jmi5, jmi6, jmi7, jmi8, jmi9,jmi10;
JTextField jtf1, jtf2, time;
JPanel jp1, jp2, jp3;
Timer timer;
TimeZone tz = TimeZone.getTimeZone("JST");
Toolkit toolkit=Toolkit.getDefaultToolkit();;
/**
* <br>
* 方法說明:實現ActionListener類必須過載的方法
*/

public static void main(String[] args) {
Clock cp = new Clock();
cp.setVisible(true);
}

Clock() {
super("Java鬧鍾!");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(550, 700);
setVisible(true);
Container contentPane = getContentPane();

jp2 = new JPanel();

jmb = new JMenuBar();

jm1 = new JMenu("背景顏色設置 ", true);
jmi1 = new JMenuItem("外圈顏色");
jmi1.addActionListener(this);
jmi1.setActionCommand("color1");
jm1.add(jmi1);
jmi2 = new JMenuItem("鬧鍾邊線顏色");
jmi2.addActionListener(this);
jmi2.setActionCommand("color2");
jm1.add(jmi2);
jmi3=new JMenuItem("底盤顏色");
jmi3.addActionListener(this);
jmi3.setActionCommand("color3");
jm1.add(jmi3);
jmi4=new JMenuItem("系統時間背靜顏色");
jmi4.addActionListener(this);
jmi4.setActionCommand("color4");
jm1.add(jmi4);
jmb.add(jm1);

jm2 = new JMenu("指針顏色設置 ", true);
jmi5 = new JMenuItem("秒針顏色");
jmi5.addActionListener(this);
jmi5.setActionCommand("color5");
jm2.add(jmi5);
jmi6 = new JMenuItem("分針顏色");
jmi6.addActionListener(this);
jmi6.setActionCommand("color6");
jm2.add(jmi6);
jmi7 = new JMenuItem("時針顏色");
jmi7.addActionListener(this);
jmi7.setActionCommand("color7");
jm2.add(jmi7);
jmb.add(jm2);

jm3 = new JMenu("鬧鈴聲音設置 ", true);
jmi8 = new JMenuItem("響鈴1");
jmi8.addActionListener(this);
jmi8.setActionCommand("ring1");
jm3.add(jmi8);
jmi9 = new JMenuItem("靜音");
jmi9.addActionListener(this);
jmi9.setActionCommand("ring2");
jm3.add(jmi9);
jmb.add(jm3);

jm4 = new JMenu("幫助 ", true);
jmi10=new JMenuItem("使用說明");
jmi10.addActionListener(this);
jmi10.setActionCommand("help");
jm4.add(jmi10);
jmb.add(jm4);
jp2.add(jmb);

contentPane.add(jp2, BorderLayout.NORTH);

jp3 = new JPanel();
jl1 = new JLabel("鬧鈴時間");
jl1.setFont(new Font("楷體_GB2312", Font.BOLD, 18));
time = new JTextField("00:00", 5);
alarm = time.getText();
jb = new JButton("修改鬧鈴時間");
jb.addActionListener(this);
jb.setActionCommand("CC");
jp3.add(jl1);
jp3.add(time);
jp3.add(jb);
contentPane.add(jp3, BorderLayout.SOUTH);

ClockPanel clock = new ClockPanel();
contentPane.add(clock, BorderLayout.CENTER);

// 窗體添加事件監聽,監聽秒錶的觸發
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
repaint();
}
};
new Timer(delay, taskPerformer).start();
}

/**
* <br>
* 方法說明:繪制圖形
*/

Color C1 = Color.lightGray;// 外圈顏色
Color C2 = Color.black;// 邊線顏色
Color C3 = Color.magenta;// 內盤顏色
Color C4 = Color.blue;// 背景顏色
Color C5 = Color.yellow;// 秒針顏色
Color C6 = Color.green;// 分針顏色
Color C7 = Color.red;//時針顏色
public class ClockPanel extends JPanel {
public void paint(Graphics g) {
h = getSize().height - 200;
// 繪制圓形
g.setColor(C1);
g.fillOval(L0 + 30, T0 + 30, h - 60, h - 60);
g.setColor(C2);
g.drawOval(L0 + 31, T0 + 31, h - 62, h - 62);
g.setColor(C3);
g.fillOval(L0 + 50, T0 + 50, h - 100, h - 100);
g.setColor(C2);
g.drawOval(L0 + 51, T0 + 51, h - 102, h - 102);

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;
g.drawString("指針式時鍾", 215, 200);

// 獲取時間
now = Calendar.getInstance();
hh = now.get(Calendar.HOUR_OF_DAY);// 小時
mm = now.get(Calendar.MINUTE);// 分鍾
ss = now.get(Calendar.SECOND);// 秒
g.setColor(C4);
g.fillRect(5, 550, 150, 30);// 填充的矩形
g.setColor(C6);
if (hh < 10)
st = "0" + hh;
else
st = "" + hh;
if (mm < 10)
st = st + ":0" + mm;
else
st = st + ":" + mm;
if(alarm.equals(st))
{
if(toolkit!=null)
toolkit.beep();
else {}
}
if (ss < 10)
st = st + ":0" + ss;
else
st = st + ":" + ss;
{
g.setFont(new Font("華文楷體", Font.BOLD, 16));
g.drawString("系統時間:" + st, 10, 570);
}

// 計算時間和圖形的關系
sdo = 90 - ss * 6;
mdo = 90 - mm * 6;
hdo = 90 - hh * 30 - mm / 2;
// 擦除秒針
if (old_X > 0) {
g.setColor(C3);
} else {
old_M = mdo;
old_H = hdo;
}
// 繪制秒針
g.setColor(C5);
x = (int) ((r - 26) * Math.cos(RAD * sdo) + x0);
y = (int) ((r - 26) * Math.sin(RAD * sdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));

old_X = x;
old_Y = y;

// 擦除分針和時針
if (mdo != old_M) {
g.setColor(C3);
old_M = mdo;
}
if (hdo != old_H) {
g.setColor(C3);
old_H = hdo;
}
// 繪制分針
g.setColor(C6);
x = (int) ((r - 50) * Math.cos(RAD * mdo) + x0);
y = (int) ((r - 50) * Math.sin(RAD * mdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));
// 繪制時針
g.setColor(C7);
x = (int) ((r - 90) * Math.cos(RAD * hdo) + x0);
y = (int) ((r - 90) * Math.sin(RAD * hdo) + y0) - 2 * T0;
g.drawLine(x0, y0, x, (h - y));
} // end paint
}

// 鬧鈴時間的判斷及實現
// 鬧鈴聲音的實現

public void actionPerformed(ActionEvent e) {
// JMenuItem m = (JMenuItem) e.getSource();

if (e.getActionCommand() == "CC") {
int newHou, newMin;
char c;

String getTime = JOptionPane.showInputDialog(this, "請輸入鬧鈴時間格式如:", "00:00");
repaint();

//如果撤消設置時間,就什麼列印null
if(getTime==null)
System.out.println(getTime);
// dispose();

judge: if (getTime != null) {
//列印輸入的設置的時間
System.out.println(getTime);
// 判斷輸入的是不是5位字元
if (getTime.length() != 5) {
JOptionPane.showMessageDialog(time, "格式錯誤\n請按格式輸入5位數字", "Error",
JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}

// 判斷輸入的是不是數字
for (int i = 0; i < (getTime.length()); i++) {
c = getTime.charAt(i);
if (i == 2 && !Character.isDigit(c))
continue;
// 判斷當前字元,如果不是數字則跳出該事件
if (i != 2 && !Character.isDigit(c)) {
JOptionPane.showMessageDialog(this, "格式錯誤\n請按格式輸入5位數字",
"Error",JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
}
char[] hour = { getTime.charAt(0), getTime.charAt(1) };
char[] minute = { getTime.charAt(3), getTime.charAt(4) };
newHou = Integer.parseInt(String.valueOf(hour));
newMin = Integer.parseInt(String.valueOf(minute));
if (newHou >= 24 || newHou < 0) {
JOptionPane.showMessageDialog(this, "格式錯誤\n小時應該是不小於0不大於23的正數",
"Error", JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
if (newMin >= 60 || newHou < 0) {
JOptionPane.showMessageDialog(this, "格式錯誤\n分鍾應該是小於60的正數", "Error",
JOptionPane.ERROR_MESSAGE);
repaint();
break judge;
}
new SetTime(newHou, newMin);
}
}

if (e.getActionCommand() == "ring1") {
toolkit=Toolkit.getDefaultToolkit();
}
if(e.getActionCommand() == "ring2"){
System.out.println("靜音");
toolkit=null;

}

if (e.getActionCommand() == "color1") {
String color;
Color c;
System.out.println("color1");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的外圈顏色(0--255)", "128");
if (color == null) {
} else {
if (Integer.parseInt(color) < 0
|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的外圈顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C1 = c;
}
}
}
if(e.getActionCommand() == "color2"){
String color;
Color c;
System.out.println("color2");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的邊線顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的邊線顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C2 = c;
}
}
}
if(e.getActionCommand() == "color3"){
String color;
Color c;
System.out.println("color3");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的內盤顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的內盤顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C3 = c;
}
}
}

if(e.getActionCommand() == "color4"){
String color;
Color c;
System.out.println("color4");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的背景顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的背景顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C4 = c;
}
}
}
if(e.getActionCommand() == "color5"){
String color;
Color c;
System.out.println("color5");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的秒針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的秒針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C5 = c;
}
}
}
if(e.getActionCommand() == "color6"){
String color;
Color c;
System.out.println("color6");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的分針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的分針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C6 = c;
}
}
}

if(e.getActionCommand() == "color7"){
String color;
Color c;
System.out.println("color7");
color = JOptionPane.showInputDialog(this, "請輸入喜歡的時針顏色(0--255)", "128");
if(color==null){}
else{if (Integer.parseInt(color) < 0|| Integer.parseInt(color) > 255)
JOptionPane.showInputDialog(this, "請輸入喜歡的時針顏色(0--255)", "128");
else {
c = new Color(Integer.parseInt(color));
C7 = c;
}
}
}

if(e.getActionCommand() == "help"){
String help;
help = JOptionPane.showInputDialog(this, "輸入quit退出該鬧鍾的使用", "這是運行在Java中的指針式時鍾");
if(help.equals("quit"))
dispose();
else {}
// timer.restart();
}
}

class SetTime {
String Hour;
String Minute;

public SetTime() { }
public SetTime(int hour, int minute) {
// 當時間參數小於10的時候在前面添加字元0
if (hour < 10) {
Hour = "0" + String.valueOf(hour);
} else {
Hour = "" + String.valueOf(hour);
}
if (minute < 10) {
Minute = "0" + String.valueOf(minute);
} else {
Minute = "" + String.valueOf(minute);
}
alarm = Hour + ":" + Minute;
time.setText(alarm);
repaint();
}
}
}

㈣ 急需要一個簡單的JAVA鬧鍾程序

寫了一個,也盡量在你可能不懂的地方添加註釋了。不過其實注釋越多不見得越好,因為有時你太在意注釋反而沒弄清整體的代碼結構。

importjava.awt.BorderLayout;
importjava.awt.FlowLayout;
importjava.awt.Font;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyEvent;
importjava.awt.event.KeyListener;
importjava.io.IOException;
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Calendar;
importjava.util.Timer;
importjava.util.TimerTask;

importjavax.sound.sampled.AudioInputStream;
importjavax.sound.sampled.AudioSystem;
importjavax.sound.sampled.Clip;
importjavax.sound.sampled.LineEvent;
importjavax.sound.sampled.LineListener;
importjavax.sound.sampled.LineUnavailableException;
importjavax.sound.sampled.UnsupportedAudioFileException;
importjavax.swing.JButton;
importjavax.swing.JDialog;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
/**
*鬧鍾主界面
*/
{
privatestaticfinalintLOOP_COUNT=5;//重復播放的次數
privateJLabellabelClock,labelAlarm,labelNextAlarm;
privateJButtonbtnSet,btnClose;
privateSetDialogsetDialog;
privateJPaneltopPanel,alarmPanel;
privateTimertimer;
privateClipclip;
privateCalendaralarmCal;
privatebooleantimeReached=true;
privateDateFormatdf=newSimpleDateFormat("HH:mm");

publicAlarmClock(){
super("鬧鍾");
}

publicvoidlaunch(){
setSize(400,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

getContentPane().setLayout(newBorderLayout());//利用邊界布局將界面分割成上中下三部分
labelAlarm=newJLabel("鬧鍾定時已到!");
btnClose=newJButton("確定");
labelNextAlarm=newJLabel();//指示下一次鬧鍾時間
alarmPanel=newJPanel(newFlowLayout(FlowLayout.CENTER));//頂部提示欄提示鬧鍾時間已到,和確定按鈕
alarmPanel.add(labelAlarm);
alarmPanel.add(btnClose);

topPanel=newJPanel(newGridLayout(2,1));
topPanel.add(alarmPanel);
topPanel.add(labelNextAlarm);
alarmPanel.setVisible(false);//初始隱藏頂部提示欄

labelClock=newJLabel();
Fontfont=newFont(Font.SERIF,Font.PLAIN,48);//中間的倒計時文本用大號字體展示
labelClock.setFont(font);
labelClock.setHorizontalAlignment(JLabel.CENTER);//文本居中
btnSet=newJButton("設置");

getContentPane().add(topPanel,BorderLayout.NORTH);//界面頂部
getContentPane().add(labelClock,BorderLayout.CENTER);//界面中部
getContentPane().add(btnSet,BorderLayout.SOUTH);//界面底部

btnSet.addActionListener(this);//設置按鈕的點擊事件
btnClose.addActionListener(this);//頂部確定按鈕的點擊事件
setLocationRelativeTo(null);//界面居中
setDialog=newSetDialog(this);//初始化設置對話框

try{//初始化鬧鍾聲音
//目前發現wav格式的文件是可以支持的,mp3不支持
AudioInputStreamais=AudioSystem.getAudioInputStream(
AlarmClock.class.getResource("/res/alarm.wav"));
clip=AudioSystem.getClip();
clip.open(ais);
ais.close();
intloop=LOOP_COUNT<=0?1:LOOP_COUNT;
finallongtotalFrames=ais.getFrameLength()*loop;
clip.addLineListener(newLineListener(){
@Override
publicvoipdate(LineEvente){
//當鬧鍾音樂播放結束時,自動隱藏頂部提示欄
if(e.getFramePosition()>=totalFrames){
stopAlarm();
}
}
});
}catch(){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(LineUnavailableExceptione){
e.printStackTrace();
}
initTimer();
}

publicstaticvoidmain(String[]args){
newAlarmClock().launch();//啟動主界面
}

@Override
publicvoidactionPerformed(ActionEvente){
Objectsource=e.getSource();
if(source==btnSet){//點擊設置按鈕時彈出設置界面,以模對話框顯示
setDialog.setVisible(true);
}elseif(source==btnClose){//點擊頂部確定按鈕時隱藏頂部提示欄
stopAlarm();
}
}

privatevoidinitTimer(){
timer=newTimer();//初始化倒計時任務
//開始倒計時
timer.scheleAtFixedRate(newTimerTask(){
@Override
publicvoidrun(){
Calendarcal=Calendar.getInstance();
inthour=cal.get(Calendar.HOUR_OF_DAY);
intmin=cal.get(Calendar.MINUTE);
intsec=cal.get(Calendar.SECOND);
//設置倒計時文本
labelClock.setText(String.format("%02d:%02d:%02d",hour,min,sec));
if(null!=alarmCal&&!timeReached){
intalarmHour=alarmCal.get(Calendar.HOUR_OF_DAY);
intalarmMin=alarmCal.get(Calendar.MINUTE);
if(alarmHour==hour&&alarmMin==min){//到時間時播放聲音
timeReached=true;
System.out.println("Timeover");
startAlarm();
}
}
}
},0,1000L);//每隔1秒刷新倒計時文本
}

/**
*開始計時
*@paramhour
*@paramminute
*/
publicvoidstartTimer(inthour,intminute){
alarmCal=Calendar.getInstance();
alarmCal.set(Calendar.HOUR_OF_DAY,hour);
alarmCal.set(Calendar.MINUTE,minute);
labelNextAlarm.setText("下次鬧鍾時間:"+df.format(alarmCal.getTime()));
timeReached=false;
}

/**
*取消倒計時任務
*/
publicvoidcancelTimer(){
labelNextAlarm.setText("");
alarmCal=null;
}

privatevoidstartAlarm(){//開始播放提示音
if(null!=clip){
alarmPanel.setVisible(true);//顯示頂部提示欄
clip.setFramePosition(0);//將音頻幀重置為第0幀
clip.loop(LOOP_COUNT);//開始循環播放
}
labelNextAlarm.setText("");
}
privatevoidstopAlarm(){//停止播放提示音
if(null!=clip&&clip.isRunning()){
clip.stop();//結束播放
}
labelNextAlarm.setText("");
alarmPanel.setVisible(false);//隱藏頂部提示欄
}

/**
*鬧鍾設置頁面
*/
,ActionListener{
privateJLabellabelHour,labelMin;
privateJTextFieldtextHour,textMin;
privateJPanelmainPanel,labelPanel,buttonPanel;
privateJButtonbtnOk,btnCancel,btnBack;
privateCalendarcal=Calendar.getInstance();

publicSetDialog(Frameframe){
super(frame);
setTitle("設置");
setModal(true);//設置為模窗口,就是說在本彈窗未消失時不允許點擊主界面。
setSize(300,150);
//顯示時分
labelHour=newJLabel("時");
labelMin=newJLabel("分");
labelHour.setHorizontalAlignment(JLabel.CENTER);
labelMin.setHorizontalAlignment(JLabel.CENTER);
textHour=newJTextField();
textMin=newJTextField();
//上面的部分用網格布局將各組件以2x2的格子放進去
labelPanel=newJPanel(newGridLayout(2,2));
labelPanel.add(labelHour);
labelPanel.add(labelMin);
labelPanel.add(textHour);
labelPanel.add(textMin);
//時分輸入框添加按鍵監聽,只允許輸入數字
textHour.addKeyListener(this);
textMin.addKeyListener(this);

//初始化按鈕
btnOk=newJButton("確定");
btnCancel=newJButton("取消");
btnBack=newJButton("返回");
//下面的按鈕依次居中放進去
buttonPanel=newJPanel(newFlowLayout(FlowLayout.CENTER));
buttonPanel.add(btnBack);
buttonPanel.add(btnCancel);
buttonPanel.add(btnOk);
//初始化主面板,將主面板分割為上下兩部分
mainPanel=newJPanel(newBorderLayout());
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);
inthour=cal.get(Calendar.HOUR_OF_DAY);
intmin=cal.get(Calendar.MINUTE);
textHour.setText(String.format("%02d",hour));
textMin.setText(String.format("%02d",min));
setLocationRelativeTo(frame);
}

@Override
publicvoidkeyPressed(KeyEventarg0){
}
@Override
publicvoidkeyReleased(KeyEventarg0){
}
@Override
publicvoidkeyTyped(KeyEvente){
intkeyChar=e.getKeyChar();
if(keyChar>=KeyEvent.VK_0&&keyChar<=KeyEvent.VK_9){
}else{//如果輸入的不是數字則屏蔽輸入
e.consume();//關鍵,屏蔽掉非法輸入
}
}

@Override
publicvoidactionPerformed(ActionEvente){
Objectsource=e.getSource();
if(source==btnOk){//如果點擊了確定按鈕,則開始計時
inthour=0,min=0;
try{
hour=Integer.parseInt(textHour.getText());
}catch(NumberFormatExceptione1){
}
try{
min=Integer.parseInt(textMin.getText());
}catch(NumberFormatExceptione1){
}
startTimer(hour,min);
setVisible(false);
}elseif(source==btnCancel){//點擊取消按鈕時取消計時
cancelTimer();
setVisible(false);
}elseif(source==btnBack){//點擊返回按鈕時什麼也不做,直接關閉設置界面
setVisible(false);
}
}
}
}

用到的音頻文件是wav格式的,你要注意mp3格式的是肯定不行的,其它格式行不行你可以自己試試。wav文件我傳到附件上吧,你如果覺得太大的話也可以自己弄一個放到指定目錄,記得重命名或修改代碼,然後再重新編譯運行。

㈤ 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 java.io.File;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
public class Alarm extends JFrame implements Runnable {
JLabel ri ,shi, fen, miao, dangqian;

JButton queding, dakai;

JTextField music,RI, SHI, FEN, MIAO;

int h=0,f=0,m=0,r=0;
boolean fo=false;
public AudioClip soumd1;
public Alarm() {
Container c = getContentPane();
c.setLayout(new GridLayout(3, 1));
JPanel jp = new JPanel();
dangqian = new JLabel();
jp.add(dangqian);
c.add(jp);
JPanel jp1 = new JPanel();
music = new JTextField(20);
dakai = new JButton("選擇鬧鈴音樂");
jp1.add(music);
jp1.add(dakai);
c.add(jp1);
ri = new JLabel("日");
RI = new JTextField(4);
shi = new JLabel("時");
SHI = new JTextField(4);
fen = new JLabel("分");
FEN = new JTextField(4);
miao = new JLabel("秒");
MIAO = new JTextField(4);
JPanel jp2 = new JPanel();
jp2.add(ri);
jp2.add(RI);
jp2.add(shi);
jp2.add(SHI);
jp2.add(fen);
jp2.add(FEN);
jp2.add(miao);
jp2.add(MIAO);
queding = new JButton("確定");
jp2.add(queding);
c.add(jp2);
setSize(400, 130);
setVisible(true);
dakai.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser(); // 實例化文件選擇器
fileChooser
.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // 設置文件選擇模式,此處為文件和目錄均可
fileChooser.setCurrentDirectory(new File(".")); // 設置文件選擇器當前目錄
fileChooser
.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File file) { // 可接受的文件類型
String name = file.getName().toLowerCase();
return name.endsWith(".wav")
|| name.endsWith(".au")
|| file.isDirectory();
}

public String getDescription() { // 文件描述
return "音樂文件(*.wav,*.au)";
}
});
if (fileChooser.showOpenDialog(Alarm.this) == JFileChooser.APPROVE_OPTION) { // 彈出文件選擇器,並判斷是否點擊了打開按鈕
String fileName = fileChooser.getSelectedFile().getAbsolutePath(); // 得到選擇文件或目錄的絕對路徑
music.setText(fileName);
}
}
});
queding.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(queding.getText().equals("確定")){
try{
r=Integer.parseInt(RI.getText());
h=Integer.parseInt(SHI.getText());
f=Integer.parseInt(FEN.getText());
m=Integer.parseInt(MIAO.getText());
if(1<=h&&h<=31&&0<=h&&h<=23&&0<=f&&f<=59&&0<=m&&m<=59)
{
fo=true;
}
else
JOptionPane.showMessageDialog(null, "輸入時間錯誤");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "請輸入正確的時間");
}

}
else
{
fo=false;
RI.setEditable(true);
SHI.setEditable(true);
FEN.setEditable(true);
MIAO.setEditable(true);
queding.setText("確定");
soumd1.stop();
}
}
});

}

public static void main(String agrs[]) {
Alarm s = new Alarm();
Thread t1 = new Thread(s);
t1.start();
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void run() {
while (true) {
Date now = new Date();
dangqian.setText("當前時間: " + now.toString());
if(fo)
{
RI.setEditable(false);
SHI.setEditable(false);
FEN.setEditable(false);
MIAO.setEditable(false);
queding.setText("關閉");
SimpleDateFormat ri=new SimpleDateFormat("dd"); //封裝 為了獲取日期
SimpleDateFormat shi=new SimpleDateFormat("kk"); //封裝 為了獲取小時
SimpleDateFormat fen=new SimpleDateFormat("mm"); //封裝 為了獲取分鍾
SimpleDateFormat miao=new SimpleDateFormat("ss"); //封裝 為了獲取秒鍾
int riqi=Integer.parseInt(ri.format(now)); //獲取日期
int shizhong=Integer.parseInt(shi.format(now)); //獲取小時
int fenzhong=Integer.parseInt(fen.format(now)); //獲取分鍾
int miaozhong=Integer.parseInt(miao.format(now)); //獲取秒鍾
if(riqi==r&&shizhong==h&&fenzhong==f&&miaozhong==m) //判斷條件
{
try {
soumd1=Applet.newAudioClip(new File(music.getText()).toURL()); //播放音樂
soumd1.loop(); //我設置的是循環播放..這樣不起床都不行..
fo=false;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}

}
}
}

㈥ 請路人幫我用JAVA製作一個小鬧鍾的程序!有賞!

給個復建議,用jfreechart插件來做,裡面有制鬧鍾控制項,不過要自己實現一些代碼。
下載頁面:
http://sourceforge.net/projects/jfreechart/files/
下載完有,把lib里的JAR導入到工程中。文件夾里還有一個JAR文件,可以運行的,裡面有個鬧鍾的例子,自己看一下把。

㈦ 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(

㈧ 跪求JAVA小鬧鍾

日歷 你可以 看「用JAVA做個簡單的程序。」這個帖 我有解答 不過我做的是某個月的 你要回年歷答 自己去加就可以了
鬧鍾 你只是要一個定時提醒的程序嗎 我不確切你的需求?如果只是定時提醒 然後鈴響了後 周期鬧鈴的話
就這樣:
比如是2010年6月12號某個時間點開始鬧鈴 鬧鈴後 每隔10分鍾再鬧一次
Calendar c = Calendar.getInstance();

c.set(Calendar.YEAR,2010);
c.set(Calendar.MONTH,5);
c.set(Calendar.DAY_OF_MONTH,12);
...設置時分秒

Date d = c.getTime();
long peroid = 10*60*1000;//毫秒數
Timer t = new Timer();
Toolkit t1 = Toolkit.getDefaultToolkit();
t.schele(new TimerTask()
{
public void run()
{
t1.beep();

}
},d,peroid);

㈨ java 使用swing製作一個小鬧鍾,包含以下功能:

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 <= 0 ? 1 : LOOP_COUNT;
final long totalFrames = ais.getFrameLength() * loop;
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent e) {
// 當鬧鍾音樂播放結束時,自動隱藏頂部提示欄
if(e.getFramePosition() >= 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(); // 啟動主界面
}

@Override
public 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.scheleAtFixedRate(new TimerTask() {
@Override
public 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);
}

@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent e) {
int keyChar = e.getKeyChar();
if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){
}else{ // 如果輸入的不是數字則屏蔽輸入
e.consume(); //關鍵,屏蔽掉非法輸入
}
}

@Override
public 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);
}
}
}
}

閱讀全文

與java小鬧鍾詳細教程相關的資料

熱點內容
電影煉獄國語版迅雷下載 瀏覽:66
女主不停生孩子系統小說 瀏覽:893
包書網txt下載 瀏覽:805
泰國罪孽父親出海 瀏覽:201
能看的網站小電影 瀏覽:460
華北電力大學javaee 瀏覽:266
練習編程可以去哪些學校 瀏覽:111
使命召喚小說同人 瀏覽:242
學校繳費用要用什麼app 瀏覽:316
聯創得力網路技術北京有限公司 瀏覽:438
按鍵精靈如何打開固定文件 瀏覽:875
小鬼當家6普通話國語 瀏覽:864
虛擬光碟機壓縮文件怎麼安裝 瀏覽:943
母女雙收的小說 文筆好 瀏覽:899
你的數據線是什麼樣的 瀏覽:530
電影開頭是一個女的洗澡 瀏覽:303
linux啟動選擇內核 瀏覽:670
華碩用什麼編程 瀏覽:277
金山數據恢復已付款怎麼辦 瀏覽:326
win10滑鼠箭頭改變 瀏覽:906

友情鏈接