需要申请Swing定时器,但是一直没有成功

Need to apply Swing timer, but haven't been sucessful

抱歉,如果我听起来很愚蠢。我才刚刚开始。我几乎没有 类 呢。 我想对我的 for 循环应用时间延迟。我尝试使用 thread.sleep 但它使整个 GUI 无法运行。有人告诉我使用 Swing 计时器来表示代码,所以我试过了。 我看过一些教程,但似乎无法正常工作。这是我的代码的一部分:

for (int d = 0; d < 201; d++) {
                    //Need to insert time delay here
                    System.out.println(jorgegress);
                    progressbard.setValue(jorgegress);
                }

这是我让它工作的尝试之一:

JButton buttond = new JButton("Click me");
        buttond.setBounds(10, 190, 416, 63);
        
        Timer timer;
        timer = new Timer(1000, null);
        timer.setRepeats(true);
        
        buttond.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("ok this works");
                for (int d = 0; d < 201; d++) {
                    //Need to insert time delay here
                    timer.start();
                    System.out.println(d);
                    progressbard.setValue(d);
                }
                timer.stop();

我做错了什么? (可能做错了很多)

试试这个代替你的 for 循环。您按下按钮将启动计时器。当计时器达到所需计数时,它会自行停止。这是非常基本的。它可以进一步定制以接受计数阈值、延迟,甚至其他方法 运行(通过 lambdas)。

Timer t = new Timer(0, new ActionListener() {
  int count = 0;
  public void actionPerformed(ActionEvent ae) {
     if (count > 201) {
         ((Timer)ae.getSource()).stop();
     }    
     System.out.println(jorgegress);
     progressboard.setValue(jorgegress);
     count++;
   }     
});
    
t.setDelay(100); // delay is in millseconds.
t.start();

您可能希望在计时器 运行ning 时锁定按钮,然后在计时器停止时重新启用它。这将防止多个计时器同时运行。