簡體   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