我有一些代码显示两个按钮的 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);
}
}