gpt4 book ai didi

java - 如何使变量在后台每秒递增

转载 作者:行者123 更新时间:2023-11-30 06:44:25 25 4
gpt4 key购买 nike

我的问题是我的代码中需要包含一个时钟。问题是,我不知道如何在不完全暂停整个代码的情况下每秒递增。有人可以告诉我更好的方法吗?或者有人可以告诉我在 java 中变量每秒可以增加多少次,这样我就可以使用 % 来计算时钟需要增加多少次。

代码:

int miniseconds = 0;
int seconds = 00;
int minutes = 00;
int hours = 00;
int day = 1;
int month = 1;
int years = 2280;
int yearLeap = years % 4;
long i;
for (i = 1000000000; i>0; i--){
seconds ++;
try{
Thread.sleep(1000);//2000ms = 2s
}catch(InterruptedException ex){
}
if (seconds == 60){
minutes ++;
seconds =0;
}

if (minutes == 60){
hours++;
minutes = 0;
}
if (hours == 24){
day++;
hours = 0;
}
if (month == 1 && day == 32 ){
month ++;
day = 1;

}
if (month == 2 && day == 30 && yearLeap == 0) {
month ++;
day = 1;
}
if (month == 2 && day == 29 && yearLeap != 0){
month ++;
day = 1;
}
if (month == 3 && day == 32){
month ++;
day = 1;
}
if (month == 4 && day == 31){
month ++;
day = 0;
}
if (month == 5 && day == 32){
month ++;
day = 0;
}
if (month == 13){
month = 1;
years ++;
}
String date = "The current time is: " +day+ "/" +month+ "/" +years+ " " +hours+ ":" +minutes+ ":" +seconds;
}

最佳答案

我在这个地址发现了以下 Java 计时器示例:http://www.asjava.com/swing/java-timer-tutorial/

该示例假设您正在使用 Java.Swing 库,并且您的应用程序需要 UI,而不是使用控制台。

<小时/>

ClockLabel.java

// An extension of the JLabel class that listens to events from a Timer object to
// update itself with the current date & time.
import java.util.Date;
import java.awt.event.*;
import javax.swing.*;

public class ClockLabel extends JLabel implements ActionListener {
public ClockLabel( ) {
super("" + new Date( ));
Timer t = new Timer(1000, this);
t.start( );
}
public void actionPerformed(ActionEvent ae) {
setText((new Date( )).toString( ));
}
}
<小时/>

ClockTest.java

import javax.swing.*;
import java.awt.*;

public class ClockTest extends JFrame {
public ClockTest( ) {
super("Timer Demo");
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ClockLabel clock = new ClockLabel( );
getContentPane( ).add(clock, BorderLayout.NORTH);
}

public static void main(String args[]) {
ClockTest ct = new ClockTest( );
ct.setVisible(true);

关于java - 如何使变量在后台每秒递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897068/

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