我想仅使用空格键启动/停止秒表。我已经制作了 KeyListeners,并且只有当您按下/释放空格键时它们才会被激活。
到目前为止我尝试过的:
我尝试创建一个秒表类,它应该计算我第一次和第二次按空格键之间的时间差。我尝试如下:
public class Stopwatch {
public Stopwatch(int i) {
long time = System.currentTimeMillis();
if(i%2==1){
System.out.println("Timer Started at: " + time);
}else{
System.out.println("Timer stopped at: " + System.currentTimeMillis());
System.out.println("Time diff: " + (time - System.currentTimeMillis()));
}
}
}
int i
每按一次空格键就会增加一次。
我知道这里的问题是每次我开始这个类(class)时,time
都会重置为System.currentTimeMillis(),因为我只按空格键。因此差值始终为 0。
如何更改此设置,以便以某种方式节省第一次按空格键的时间?
这是带有 Keylistener 的类。忽略 Scrambler 类,它与我的问题无关。
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class StoppuhrFrame extends JFrame {
JLabel time, scramble;
public StoppuhrFrame() {
time = new JLabel("00:00:00");
time.setBounds(162, 45, 325, 80);
time.setFont(new Font("Arial", 100, 80));
add(time);
scramble = new JLabel("Scramble: ");
scramble.setBounds(165, 15, 370, 16);
add(scramble);
//Scrambler scrambler = new Scrambler(scramble);
addKeyListener(new timer());
setTitle("Cube Timer");
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(650, 270);
setVisible(true);
}
int i = 1;
public class timer implements KeyListener {
@Override
public void keyPressed(KeyEvent keyEvent) {
if(keyEvent.getKeyCode()==32){
new Stopwatch(i);
i++;
}
@Override
public void keyReleased(KeyEvent arg0) {
if (arg0.getKeyCode() == 32) {
if(i%2==0){
//new Scrambler(scramble);
}
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
}
提前致谢。
最佳答案
抱歉,我尝试将其添加为评论,但不允许我发布代码。 这是我提到的示例类:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Example implements KeyListener {
private static long hitTime = -1;
@Override
public void keyPressed(KeyEvent arg0) {
// This will allways return the time when first space bar was clicked
long start = getHitTime();
long actualTime = System.currentTimeMillis();
// In this case get the seconds..
long diff = (actualTime - start) / 1000;
System.out.println(String.format("TIme diff: %s", diff));
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public synchronized static long getHitTime() {
if (hitTime < 0) {
hitTime = System.currentTimeMillis();
}
return hitTime;
}
}
您也不需要秒表类,因为时间将在第一次按键点击后开始流逝(在这种情况下,未检测到特定按键,因此任何按键点击都会触发事件),并且将计算第一次点击和第二次点击之间的时间差最后一个以毫秒为单位,我将其除以一千以获得两次点击之间的秒数。
希望这有帮助
关于java - 如何仅使用空格键启动/停止秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40587641/