gpt4 book ai didi

JAVA按钮点击之间所花费的时间

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:45 25 4
gpt4 key购买 nike

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

这将为您提供第一次点击和第二次点击之间的差异

关于JAVA按钮点击之间所花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com