我有一些代码显示两个按钮的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);
}
}
答案 0 :(得分:1)
在按钮的第一次点击中设置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");
}
这将为您提供第一次点击和第二次点击之间的区别
答案 1 :(得分:0)
在您的代码中:
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
。
答案 2 :(得分:0)
使用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);
}
}