计数器关闭 JFrame,弹出确认对话框

发布于 2024-12-06 10:59:23 字数 1961 浏览 1 评论 0原文

这篇文章与我上一篇关于计时器的文章相关。我决定要立即得到结果,最简单的方法就是编写一个计数器线程,从某个时间(在本例中为 5 秒)开始倒计时,如果计数器达到 0,JFrame 将关闭,让用户知道时间已过期。

然而,我遇到了一些麻烦。当计数器达到 0 时,我似乎无法关闭 JFrame。我不确定我是否错过了一些愚蠢的东西,或者我是否误解了线程的工作方式和 JFrame 的工作方式。这是代码,让我知道你的想法。

顺便说一句,我知道使用 swing.Timer 可能是最有效的,但我还不太了解它们的本质。我受到自我施加的时间限制(我不是学生或任何人,我只是想保持动力),所以我现在正在“偷工减料”这件事。

不管怎样,先上代码吧!

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

public class RacerDoom extends JFrame {

boolean timesUp=false;

public RacerDoom() {
//create JFrame
super("Racer Doom Squared");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
if(timesUp==true) {
dispose();
JOptionPane.showConfirmDialog(null, "Time's Up! Click Okay to try again!");
}

Counter c1 = new Counter();
c1.start();

//Counter
private class Counter extends Thread {
public Counter() {}
public void run() {
for(int i=5;i>=0;i--) {
if(i==0) {
timesUp=true;
}
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
...

编辑:我已经实现并运行了计时器。它完全符合我的需要,但我无法让 timer.stop(); 命令工作。我收到错误“局部变量计时器可能尚未初始化。

就像我说的,计时器会工作,它只是永远不会停止工作,直到程序终止。这是计时器所在的 JFrame 的构造函数代码。

int counter = 0;

public RacerDoom() {
    //create JFrame
    super("Racer Doom Squared");
    setSize(WIDTH,HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    final Timer timer=new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(counter>=10) {
                timer.stop();  //the error occurs here
                dispose();
                JOptionPane.showConfirmDialog(null, "Time's Up!");
            }
            else{
               counter++;
               }
            System.out.println(counter);
        }
    });

    //inner thread
    Move1 m1 = new Move1();
    m1.start();

    timer.start();
    }

This post relates to my last one regarding a timer. I decided the easiest thing to do for immediate results was to just write a Counter thread that counts down from a certain time (in this case 5 seconds) and if the counter reaches 0, the JFrame closes and let's the user know that time has expired.

I'm running into some trouble, however. I cannot seem to make the JFrame close when the counter reaches 0. I'm not sure if I'm missing something stupid or if I am misunderstanding the way threads work and the way JFrames work. Here is the code, let me know what you think.

On a side note, I understand it would probably be most efficient to use a swing.Timer, but I just don't quite grasp the nature of them yet. I'm under self-imposed time constraints (I'm not a student or anything, I just like to stay motivated) and so I'm "jerry-rigging" this thing for now.

Anyway, on to the code!

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

public class RacerDoom extends JFrame {

boolean timesUp=false;

public RacerDoom() {
//create JFrame
super("Racer Doom Squared");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
if(timesUp==true) {
dispose();
JOptionPane.showConfirmDialog(null, "Time's Up! Click Okay to try again!");
}

Counter c1 = new Counter();
c1.start();

//Counter
private class Counter extends Thread {
public Counter() {}
public void run() {
for(int i=5;i>=0;i--) {
if(i==0) {
timesUp=true;
}
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
...

EDIT: I have the timer implemented and working. It does exactly what I need it to, but I can't get the timer.stop(); command to work. I get the error "The local variable timer may not have been initialized.

Like I said, the timer works, it just never stops working until the program is terminated. Here is the constructor code for the JFrame, where the timer is located.

int counter = 0;

public RacerDoom() {
    //create JFrame
    super("Racer Doom Squared");
    setSize(WIDTH,HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    final Timer timer=new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(counter>=10) {
                timer.stop();  //the error occurs here
                dispose();
                JOptionPane.showConfirmDialog(null, "Time's Up!");
            }
            else{
               counter++;
               }
            System.out.println(counter);
        }
    });

    //inner thread
    Move1 m1 = new Move1();
    m1.start();

    timer.start();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡绿茶香 2024-12-13 10:59:23

借助摆动计时器,这很容易做到。请参阅此代码示例:

final java.swing.Timer timer=new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(counter>5) {
                timer.stop();
                <dispose the fram here>
            }else{
               counter++;
               }
        }
    });
    timer.start();

我将此代码放入 JFrame 的构造函数中,该构造函数将在事件发送线程中运行。如果您不想挂起 GUI,请确保在另一个线程上运行此计时器,并且在处理 JFrame 时使用 SwingUtilities.invokeLater() 包装调用 - 这可确保调用在事件发送线程上排队。

我认为您的代码无法正常工作的原因相同,您尝试执行的操作未在事件发送线程中排队。这是一篇文章,可以帮助您

http://java.sun .com/products/jfc/tsc/articles/threads/threads1.html

Thats easy to do with the help of a swing timer.. See this code sample:

final java.swing.Timer timer=new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(counter>5) {
                timer.stop();
                <dispose the fram here>
            }else{
               counter++;
               }
        }
    });
    timer.start();

I put this code in the constructor of my JFrame which will run in the Event despatch thread. If you dont want hang up your GUI, make sure that you run this timer on another thread and when you are disposing the JFrame wrap the call with SwingUtilities.invokeLater() - This ensures that the call gets queued on the event despatch thread.

I think your code is not working for the same reason, that you trying to something that does not get queued up in the event despatch thread. Here's an article that will get you going

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文