gpt4 book ai didi

Java Swing.Timer 获取实时毫秒数

转载 作者:行者123 更新时间:2023-11-29 05:18:43 26 4
gpt4 key购买 nike

我的程序有问题。我想在 1 秒内获得等于 1000 的实时毫秒。这是我的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

class lsen implements ActionListener{
int ms = 0;
int s = 0;
int m = 0;

public void actionPerformed(ActionEvent e){
this.ms++;

if(this.ms == 500){
this.s++;
this.ms = 0;
}
if(this.s == 60){
this.m++;
this.s = 0;
}
}

public int getMS(){
return this.ms;
}
public int getSS(){
return this.s;
}
public int getMM(){
return this.m;
}
}

public class stopwatch_main{
public static void main(String[] args) {
lsen l = new lsen();
Timer t = new Timer(0,l);
t. start();
while(true){
System.out.println(l.getMM()+":"+l.getSS()+":"+l.getMS());
}
}
}

除了声明一个整数并递增它之外,还有其他方法可以获取毫秒吗?

最佳答案

  1. 您将希望摆脱 while (true) 而是使用 Swing Timer 代替它,因为这就是 Timer 的用途——在 Swing GUI 中重复调用 < strong>无需求助于线程中断 while (true) 构造。
  2. 你会想要给你的定时器一个合理的延迟时间。 0?常识告诉你不要使用这个。 12、15——更好。
  3. 要使 Swing 计时器工作,您需要有一个 Activity 的 Swing 事件线程,这可以通过显示 Swing GUI、任何 GUI(例如 JOptionPane)来获得。

例如:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

class Lsen implements ActionListener {
public static final int MSECS_PER_SEC = 1000;
public static final int SECS_PER_MIN = 60;
public static final int MIN_PER_HR = 60;
private static final String TIME_FORMAT = "%02d:%02d:%02d:%03d";

private long startTime;
private JTextField timeField;

public Lsen(JTextField timeField) {
this.timeField = timeField;
}

public void actionPerformed(ActionEvent e) {
if (startTime == 0L) {
startTime = System.currentTimeMillis();
} else {
long currentTime = System.currentTimeMillis();
int diffTime = (int) (currentTime - startTime);

int mSecs = diffTime % MSECS_PER_SEC;
diffTime /= MSECS_PER_SEC;

int sec = diffTime % SECS_PER_MIN;
diffTime /= SECS_PER_MIN;

int min = diffTime % MIN_PER_HR;
diffTime /= MIN_PER_HR;

int hours = diffTime;

String time = String.format(TIME_FORMAT, hours, min, sec, mSecs);
// System.out.println("Time: " + time);
timeField.setText(time);
}
}
}

public class StopWatchMain {
private static final int TIMER_DELAY = 15;

public static void main(String[] args) {
final JTextField timeField = new JTextField(10);
timeField.setEditable(false);
timeField.setFocusable(false);
JPanel panel = new JPanel();
panel.add(new JLabel("Elapsed Time:"));
panel.add(timeField);

Lsen l = new Lsen(timeField);
Timer t = new Timer(TIMER_DELAY, l);
t.start();
JOptionPane.showMessageDialog(null, panel);
t.stop();
}
}

编辑
你问的是long数据类型的意思。请看这里:Primitive Data Types .您会看到 long 表示长整数,因此您可以认为它与 int 类似,但能够容忍更大的正值和负值而不会溢出。

关于Java Swing.Timer 获取实时毫秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592688/

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