简单的计时器实现(JFrame)

设计一个图形用户界面的计时器。该计时器显示计时的时间,并有三个按钮:START,表示开始计时;STOP,停止计时;RESET,重置时间。

代码:
import java.awt.*;
import java.awt.event.*;


import javax.swing.*;


public class Main extends JFrame {
JButton jbtStart, jbtStop, jbtReset;
int hour = 0, minute = 0, second = 0;
String time = "0"+hour + ":0" + minute + ":0" + second;
Font font = new Font("TimesRoman", Font.BOLD, 40);
TimePanel timePanel;
Timer timer;


public Main() {
timePanel = new TimePanel();
jbtStart = new JButton("Start");
jbtStop = new JButton("Stop");
jbtReset = new JButton("Reset");
jbtStart.addActionListener(new ActionListener() {


@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
timer.start();
}


});
jbtStop.addActionListener(new ActionListener() {


@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
timer.stop();
}


});
jbtReset.addActionListener(new ActionListener(){


@Override

public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
hour = 0;
minute = 0;
second = -1; 

timer.restart();
}


});
JPanel p1 = new JPanel();


p1.add(jbtStart);
p1.add(jbtStop);
p1.add(jbtReset);


this.add(p1, BorderLayout.SOUTH);
this.add(timePanel, BorderLayout.CENTER);
}


class TimePanel extends JPanel {
TimePanel() {
timer = new Timer(100, new ActionListener() {


@Override
public void actionPerformed(ActionEvent arg0) {
second++;
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
if(second< 10 && hour>=10 && minute>=10)
time = hour + ":" + minute + ":0" + second;
else if(second>= 10 && hour<10 && minute>=10)
time = "0"+hour + ":" + minute + ":" + second;
else if(second>= 10 && hour>=10 && minute<10)
time = +hour + ":0" + minute + ":" + second;
else if(second< 10 && hour<10 && minute<10)
time = "0"+hour + ":0" + minute + ":0" + second;
else if(second< 10 && hour<10 && minute>=10)
time = "0"+hour + ":" + minute + ":0" + second;
else if(second>= 10 && hour<10 && minute<10)
time = "0"+hour + ":0" + minute + ":" + second;
else if(second< 10 && hour>=10 && minute<10)
time = hour + ":0" + minute + ":0" + second;
else
time = hour + ":" + minute + ":" + second;
// TODO Auto-generated method stub
repaint();
}


});
}


protected void paintComponent(Graphics g) {
super.paintComponent(g);


g.setFont(font);
int stringWidth = g.getFontMetrics().stringWidth(time);
int xCoordinate = getWidth() / 2 - stringWidth / 2;
int yCoordinate = getHeight() / 2 + stringWidth / 4;
g.drawString(time, xCoordinate, yCoordinate);
}
}


public static void main(String[] args) {
JFrame frame = new Main();
frame.setTitle("Timer");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}


}


转载于:https://www.cnblogs.com/qusay/p/4170265.html

你可能感兴趣的:(简单的计时器实现(JFrame))