看书觉得很容易,真正写代码才发现真不容易,累死。

我也是JAVA初学者(学了不到半年)32313133353236313431303231363533e58685e5aeb931333234333265,代码肯定有不合适的地方,凑合看吧,反正功能是完成了,代码如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestClock extends JFrame{
/** Creates a new instance of TestClock */
public TestClock() {
JPanel jp=new JPanel();
final JLabel jl=new JLabel("0");
jp.add(jl);
add(jp,BorderLayout.CENTER);
JButton jbStart=new JButton("开始");
jbStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton j =(JButton)e.getSource();
j.setEnabled(false);
dt=new DamThread(new ClockThread(jl));
dt.start();
}
});
JButton jbPause=new JButton("暂停");
jbPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton j=(JButton)e.getSource();
String s=(String)e.getActionCommand();
if(s.equals("暂停")){
dt.setStatus(ClockStatus.PAUSE);
j.setText("继续");
}else{
dt.setStatus(ClockStatus.CONTINUE);
j.setText("暂停");
}
}
});
JButton jbZero=new JButton("清零");
jbZero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dt.setStatus(ClockStatus.ZERO);
}
});
JButton jbStop=new JButton("停止");
jbStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dt.setStatus(ClockStatus.STOP);
}
});
JPanel jp1=new JPanel();
jp1.add(jbStart);
jp1.add(jbPause);
jp1.add(jbZero);
jp1.add(jbStop);
add(jp1,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
TestClock tc=new TestClock();
tc.setVisible(true);
}
DamThread dt;
}
class DamThread extends Thread{
public DamThread(ClockThread c){
this.ct=c;
ct.start();
this.setDaemon(true);
this.STATUS=ClockStatus.START;
}
public void run(){
while(ct.isAlive()){
CheckStatus();
}
}
private void CheckStatus(){
switch(getStatus()){
case PAUSE:
ct.mysuspend();
break;
case ZERO:
ct.seti(0);
ct.label.setText("0");
setStatus(ClockStatus.START);
break;
case STOP:
ct.seti(1001);
break;
case CONTINUE:
ct.myresume();
break;
default:
break;
}
}
public void setStatus(ClockStatus cs){
this.STATUS=cs;
}
public ClockStatus getStatus(){
return STATUS;
}
ClockStatus STATUS;
ClockThread ct;
}
class ClockThread extends Thread{
public ClockThread(JLabel j){
this.label=j;
suspendFlag=false;
}
public void run(){
while(i<=1000){
try {
i++;
label.setText(""+i);
synchronized(this){
while(suspendFlag){
wait();
}
}
sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void seti(int in){
this.i=in;
}
public void mysuspend()
{
suspendFlag=true;
}
synchronized void myresume()
{
suspendFlag=false;
notify();
}
private boolean suspendFlag;
private int i=0;
JLabel label;
}
enum ClockStatus{
START,PAUSE,ZERO,STOP,CONTINUE
}