我想用Java设计一个计时器,比如我设置时间为1988年12月20日13点18分20秒开始,当点击结束按钮时能计算出从开始到结束过了多少秒。最好能给出代码。

解决方案 »

  1.   

    你可以在点击开始按钮时,设置一个startTime变量,用Date或者Calendar都可以,记录开始的时间,当点击结束按钮时,在获得一个当前的时间endTime两个变量,如果是Calendar对象可以通过compareTo方法比较,应该会的到这两个日期相差的毫秒数,然后你把这个毫秒转成秒,就可以了O(∩_∩)O~
      

  2.   


    代码结构不是很好,有些问题没考虑:如点击开始按钮后才能激活停止按钮但你说到功能实现了自己去用扩充,才能有进步祝你成功!!!
    package com.xiaoyong;import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;@SuppressWarnings("serial")
    public class Timer extends JFrame implements ActionListener { private JButton start;
    private JButton stop; private JTextField field;
    private JLabel jLabel; long startTime;
    long stopTime; public Timer() {
    start = new JButton("start");
    stop = new JButton("stop");
    start.addActionListener(this);
    stop.addActionListener(this);
    this.setSize(new Dimension(400, 200));
    this.setResizable(false);
    this.getContentPane().setLayout(new BorderLayout());
    JPanel panel = new JPanel(new GridLayout(1, 2));
    panel.add(start);
    panel.add(stop);
    this.getContentPane().add(panel, BorderLayout.SOUTH);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jLabel = new JLabel("运行时间:");
    field = new JTextField();
    JPanel jPanel = new JPanel(new GridLayout(1, 2));
    jPanel.add(jLabel);
    jPanel.add(field); this.getContentPane().add(jPanel, BorderLayout.CENTER);
    } @Override
    public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    if (button == start) {
    startTime = System.currentTimeMillis();
    this.field.setText("");
    } else if (button == stop) {
    stopTime = System.currentTimeMillis();
    long time = stopTime - startTime;
    this.field.setText(Long.toString(time)+"秒");
    }
    } public static void main(String[] args) {
    new Timer().setVisible(true);
    }}
      

  3.   

    或者还有一个System.currentTimeMillis()这个方法返回系统的毫秒时间,long型,你可以通过两次调用这个函数,获得两个long值相减也可O(∩_∩)O~