繁体   English   中英

定时器延迟不能正常工作

[英]Timer delay doesn't work properly

编辑后的帖子:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Examp{
JFrame field;
JPanel squares[][] = new JPanel[10][6];

public Examp(){
    field = new JFrame("Football Game");
    field.setSize(600, 800);
    field.setLayout(new GridLayout(10, 6));

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            squares[i][j] = new JPanel();
            if (j == 2 || j == 3)
            {
                if (i == 0)
                    squares[i][j].setBackground(Color.RED);
                else if (i == 9)
                    squares[i][j].setBackground(Color.BLUE);
                else
                    squares[i][j].setBackground(Color.GREEN);
            }
            else
            {
                squares[i][j].setBackground(Color.GREEN);
            }
            field.add(squares[i][j]);
        }
    }

    field.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    field.setVisible(true);
}

public void place(int i,int j){
    ImageIcon ballIcon = new ImageIcon("C:\\Users\\Pamvotis\\Desktop\\Project\\img\\icon.png");
    JLabel ball = new JLabel(ballIcon);
    squares[i][j].add(ball);

    field.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    field.setVisible(true);
}

public void clear(){
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            squares[i][j].removeAll();
        }
    }
    field.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    field.setVisible(true);
}

public static void main(String[] args){
    Examp football = new Examp();
    football.place(2,3);
    Timer timer = new Timer(1000, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
          football.clear();
          System.out.println("happened");
        }
    });
  timer.setRepeats(false);
  timer.start();

}

}

所以我已经编辑并尝试简化代码,以便您可以更好地理解我的要求,我之前对此表示歉意。

基本上我想要的是在 1 秒后清除所有图标的字段(我想制作一场足球比赛,所以我用它来看看它如何在更大的范围内工作,我将在每轮比赛后删除所有内容以添加新职位)。 我的问题是 clear() 方法在 Timer 中时似乎没有被执行(如果我在外面执行它会很好地执行)。 我的 System.out.println(...) 在 Timer 中也以适当的延迟执行得很好,所以我真的不明白问题是什么。 谁能帮我?

clear(...)方法实际上很可能会被执行,如果你在里面放一个 println ,你肯定会知道。 问题是,它是否在正确的对象上执行?

我猜你的 Game 类有它自己的 Graphics 对象(顺便说一句,一个可怕的类名,因为它直接与java.awt.Graphics类发生冲突,而那是需要改变其状态的。一个可能的解决方案是给 Game 一个允许外部类改变其状态的方法。

不过,为了获得更好的答案,请发布一个更好的信息更丰富的问题​​,一个带有更相关代码的问题。

也许更好的是使字段 int counter 示例 int counter =1; 并且在计时器任务中,您可以将计数器减 1。因此计数器将具有新值 0。在您需要检查的地方,您可以检查计数器的值是否为 0,如果是,您可以调用您的方法 Football.clear();

更新:

   public int counter=1;

   *********

   Timer timer = new Timer(1000, new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
         counter--;
     }
   });
 timer.start();
}

***********

if(counter==1){
  football.clear();
  System.out.println("happened");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM