两次按钮点击之间的时间(Java)

时间:2014-10-12 15:19:03

标签: java button time

我想打印两次按键点击之间的时间(ButtonA和ButtonB)。这是我的代码的一部分(由于只打印了当前时间,因此不起作用):

class ClicksReporter implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
  long startTime = 0;
  long endTime = 0;

  if ( e.getActionCommand().equals("ButtonA") ) {
    System.out.println("ButtonA was clicked");
    startTime = System.currentTimeMillis()/1000;
  } 

  if ( e.getActionCommand().equals("ButtonB") ) {
    System.out.println("ButtonB was clicked");
    endTime = System.currentTimeMillis()/1000 - startTime;
    System.out.println("Time: "+endTime);    
  }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

startTimeendTime是方法返回后丢失的局部变量。因此,每次点击ButtonB时,startTime的值都为零。你需要让开始时间成为类的一个字段。所以,像这样:

class ClicksReporter implements ActionListener {
  long startTime=0;
  @Override
  public void actionPerformed(ActionEvent e) {
  if ( e.getActionCommand().equals("ButtonA") ) {
    System.out.println("ButtonA was clicked");
    this.startTime = System.currentTimeMillis()/1000;
  } 

  if ( e.getActionCommand().equals("ButtonB") ) {
    System.out.println("ButtonB was clicked");
    long endTime = System.currentTimeMillis()/1000 - startTime;
    System.out.println("Time: "+endTime);    
  }
}

此外,请确保将ClicksReporter的相同实例设置为按钮A和B的动作侦听器。