[英]JAVA time it takes between button clicks
我有一些代碼顯示了兩個按鈕的GUI,目標是按下一個按鈕兩次以顯示兩次單擊之間花費的時間(以毫秒為單位)。
盡管我的問題是時間始終為0。有什么建議嗎? 我還想實現一種方法來獲取按鈕a和按鈕b的單擊之間的時間。 有小費嗎? 謝謝。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonViewer
{
static int countA = 0;
static int countB = 0;
public static void main( String[] args )
{
JFrame frame = new JFrame();
GridLayout layout = new GridLayout(2,2);
frame.setLayout(layout);
JButton buttonA = new JButton("Button A");
frame.add(buttonA);
class ClickListenerOne implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
countA++;
long StartA = System.currentTimeMillis();
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis();
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");
}
}
}
JButton buttonB = new JButton("Button B");
frame.add(buttonB);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
countB++;
long StartB = System.currentTimeMillis();
if (countB % 2 == 0)
{
long EndB = System.currentTimeMillis();
long differenceB = (EndB - StartB);
System.out.println(differenceB + " Elapsed");
}
}
}
ActionListener mButtonAClicked = new ClickListenerOne();
buttonA.addActionListener(mButtonAClicked);
ActionListener mButtonBClicked = new ClickListenerTwo();
buttonB.addActionListener(mButtonBClicked);
frame.setSize( 200, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible(true);
}
}
在按鈕的第一次單擊中設置StartA,即
long StartA;
public void actionPerformed( ActionEvent event )
{
countA++;
if (countA % 2 != 0)
StartA = System.currentTimeMillis();
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis();
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");
}
這將為您提供第一次點擊和第二次點擊之間的區別
在您的代碼中:
class ClickListenerOne implements ActionListener {
// int startA; ?
public void actionPerformed( ActionEvent event )
{
countA++;
long StartA = System.currentTimeMillis(); // you are reading time
//after mouse click event
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis(); // variable name should not be
//declared with capital letter
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");// then you are computing
//elapsed time in the same click event
// startA = endA; // updated the time after each event?
}
}}
這樣,您將不會在隨后的鼠標單擊事件之間花費時間。 想法是將startTime
聲明為類減速中的成員。 在執行操作時計算經過的時間,然后通過將startTime
設置為endTime
來更新它。
使用System.nanotime()代替System.currentTimeMillis()
public void actionPerformed( ActionEvent event )
{
countA++;
if(countA % 2 != 0){
StartA = System.nanoTime();
}
if (countA % 2 == 0)
{
EndA = System.nanoTime();
differenceA = EndA- StartA;
System.out.println(differenceA);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.