gpt4 book ai didi

java - 在 JFrame 内创建倒计时器

转载 作者:行者123 更新时间:2023-12-01 09:44:33 25 4
gpt4 key购买 nike

我已经在这个问题上苦苦挣扎了一段时间,所以我想我应该寻求一些帮助。

我正在为一个游戏创建一个应用程序,它需要我制作一个动态倒计时器。我所说的动态是指能够以消费者的身份放入您想要的倒计时器。我遇到的问题是让我的代码等待 1000 毫秒才能在正确的时间执行更新代码。我正在尝试使用 sleep 功能来执行此操作...

这不是我正在制作的应用程序,这只是为了尽可能地为愿意帮助我的人简化我的问题。这里的所有内容都直接来自 Eclipse IDE 中的 WindowBuilder。我遇到的问题是让 Thread thread = new Thread();Thread.sleep(1000); 一起工作以实现完整的 1 秒延迟。

package test;

import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import java.awt.Font;

public class test {

private JFrame frame;

/**
*
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}




/**
* Create the application.
*/
public test() {
initialize();
}

/**
* Initialize the contents of the frame.
*/



private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.RED);

JLabel lblNewLabel = new JLabel("Test");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 62));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(lblNewLabel, BorderLayout.CENTER);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Thread thread = new Thread();

for(int i = 60;i>=0;i--){
thread.sleep(500);
lblNewLabel.setText("Test" + i);
}

}

}

如果您将此代码放入 IDE 中,则会出现Unhandled exception InterruptedException 错误。如果我添加 throws 声明,代码就会把一切搞乱,说实话我不知道问题出在哪里。

如何修复或解决此问题?

最佳答案

这是另一种方法。请注意此代码未经测试。

private void initialize() {
...
new Thread() {
int counter = 10;
public void run() {
while(counter >= 0) {
lblNewLabel.setText("Test" + (counter--));
try{
Thread.sleep(1000);
} catch(Exception e) {}
}
}
}.start();
}

关于java - 在 JFrame 内创建倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175659/

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