我如何滥用javax.swing.Timer?

时间:2014-03-12 18:20:14

标签: java swing timer

在这里,我创建了一个游戏,您可以在其中掷骰子并一次绘制一个错误。这是 什么卷的列表可以为您提供哪些部分以及您需要的数量。

  • 1 - 身体(需要一个)
  • 2 - 头(需要一个;必须先拥有一个身体)
  • 3 - 眼睛(需要两个,首先必须有头)
  • 4 - 天线(需要两个;必须先头部)
  • 5 - 腿(需要6个;必须先身体)
  • 6 - 尾巴(需要一个;必须先拥有身体)

您必须点击身体部位附近的屏幕才能显示出来。然后我们 可以计时整件事。

我使用Panel来处理我的计时器,但我没有得到什么问题?

主程序

package dice;

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

public class Yahtzee extends JFrame implements ActionListener 
{
  Die[] d; // array to hold the 5 dice
  FourOfAKind[] f;
  JPanel buttonPanel; // panel for the timer
  JPanel dicePanel; // panel to hold the dice
  JPanel bugPanel;
  ScoreRow[] theScores;

  protected Object bug;

   public static void main(String[] args) {
    Yahtzee y = new Yahtzee();
   }

    public Yahtzee() 
    {
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());
    setLayout(new BorderLayout());

    dicePanel = new JPanel();
    dicePanel.setLayout(new GridLayout(5, 1));
    dicePanel.setLayout(new FlowLayout());
    dicePanel.setSize(new Dimension(50, 50));

    add(dicePanel, BorderLayout.CENTER);
    d = new Die[1];
    for (int i = 0; i < 1; i++) {
        d[i] = new Die(this);
        dicePanel.add(d[i]);
    }

    bugPanel = new JPanel();
    bugPanel.setLayout(new GridLayout(5, 5));
    bugPanel.setLayout(new FlowLayout());
    bugPanel.setSize(new Dimension(50, 50));

    add(bugPanel, BorderLayout.SOUTH);
    f = new FourOfAKind[1];
    for (int w = 0; w < 1; w++) {
        f[w] = new FourOfAKind(this);
        bugPanel.add(f[w]);
    }
    setSize(new Dimension(715, 705));
    setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
    repaint();

}

public void setChoice(int choice) 
{
    f[0].setChoice(choice);
}

public void drawBug() 
{
    f[0].setChoice(d[0].getChoice());
    f[0].drawBug();
}

    }

我注释掉了那些没有编译的计时器。

1 个答案:

答案 0 :(得分:2)

  

“我希望在我完成绘制我的错误之后,我会点击面板并停止计时器,看看它需要多长时间来绘制错误。”

您根本不需要Timer 。如果您没有在UI中更新任何内容,那么就不需要它了。

您可以通过其他方式跟踪时间。一种方法是,只要您想开始跟踪时间,只需使用System.currentTimeMiilis()即可。有一个全局变量long startTime并在你想要时钟开始时设置它

long startTime;
...
startTime = System.currentTimeMillis();

当您想要停止时钟时,只需再次执行并减去差异

long endTime = System.currentTimeMillis();
long elapsedMillis = endTime - startTime;
long elapsedSeconds = elapsedMillis / 1000;