java.util.Timer&&摇摆不幸

时间:2016-09-29 19:48:56

标签: java multithreading swing timer windowlistener

目前,我正在制作一款基于回合制的游戏,其中包含剩余时间的JLabel,其他几个问题/答案/团队分数标签以及游戏板主面板。

此代码的第一个问题:GameTimer类经常被调用,I.E。它不是每秒都被调用,而是每秒约5-10次。 (输出“Timer:”+ timeElapsed的打印语句在大约10秒内打印每个数字大约80(定时器:1,定时器:2等)。作为旁注,问题的时间永远不会超过15 while循环在它变得混乱之前不应该停止吗?这个问题偶尔会发生。我认为这是一个与util.Timer相关的错误,不在我的代码中,但是我不太熟悉类的内部工作原理

第二个问题:for:在一个无限循环中调用每个循环,就像它打印“Reached Questions。问题数量:”+ questions.size()并继续到for:每个循环无限期。我不认为windowOpened()可以多次调用,而且我也使用了windowActivated(),结果相同。

最终问题:时间标签仅在timeElapsed超过question.getTime后更新,这意味着标签中只有一个负数。 while循环应该检测到timeElapsed更大,并且停止,但它没有。

我对所有这些感到困惑,非常感谢任何帮助。

项目的一点历史:在实现windowListener之前,类在执行for:each循环之前等待了30秒,因为在计时器完成之前窗口将是灰色屏幕(已卸载),所以它不起作用,并且然后它会正常加载,但GameTimer在30秒计时器后立即启动。然后我尝试使用线程每秒更新一次,但这与之前的尝试有类似的问题。

除此之外还有其他课程。这两个是我认为错误在其中的:

游戏屏幕代码:

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.util.*;
import java.awt.event.*;

@SuppressWarnings("deprecation")
public class GameScreen implements WindowListener{
    private int team1Score = 0;
    private int team2Score = 0;
    private ArrayList<Question> questions;

    private Question cQuestion;

    private boolean start = false;

    private boolean timesUp = false;
    private boolean isCorrect = false;
    private java.util.Timer timer = new java.util.Timer();
    private int timeElapsed = 0;

    private boolean isTeam1 = true;

    private String correctAnswer = "";
    private String inputAnswer = "";
    private int numIncorrect = 0;

    private TopPanel topPanel = new TopPanel();

    public GameScreen(ArrayList<Question> questions) {
        JFrame gameFrame = new JFrame("Cavazos Math Game");

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int width = (int)screenSize.getWidth();
        int height = (int)screenSize.getHeight();

        gameFrame.setSize(width, height);
        gameFrame.setResizable(false);
        gameFrame.setLocationRelativeTo(null);
        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        topPanel.setSize(width, 200);

        this.questions = questions;

        BorderLayout layout = new BorderLayout();

        gameFrame.setLayout(layout);

        System.out.println("Reached Image Loading");

        try {
            BufferedImage fieldImage = ImageIO.read(new File("field2.png"));
            GamePanel gamePanel = new GamePanel(fieldImage);
            gamePanel.setSize(width, height - 200);
            gameFrame.add(gamePanel, BorderLayout.CENTER);
        }
        catch(Exception e) {System.out.println("RUH ROH");}

        System.out.println("Reached Layout Loading");

        gameFrame.add(topPanel, BorderLayout.NORTH);
        gameFrame.setVisible(true);

        gameFrame.addKeyListener(topPanel);

        gameFrame.addWindowListener(this);
    }

    public void windowDeactivated(WindowEvent e) {}

    public void windowIconified(WindowEvent e) {}

    public void windowDeiconified(WindowEvent e) {}

    public void windowClosed(WindowEvent e) {}

    public void windowClosing(WindowEvent e) {}

    public void windowActivated(WindowEvent e) {}

    public void windowOpened(WindowEvent e) {
        System.out.println("Reached Questions. Number of question: " + questions.size());

        for(Question question : questions) {
            timeElapsed = 0;
            cQuestion = question;
            timesUp = false;
            topPanel.setQuestion(question.getQuestionString());
            setTimer(question.getTime());
            correctAnswer = question.getAnswer();
            System.out.println(question.getTime() + "");
            while((timeElapsed < question.getTime()) && !isCorrect && (numIncorrect <= 4)) {
                if(!topPanel.getInput().equals("nothing")) { //has an answer been submitted?
                    inputAnswer = topPanel.getInput();
                    if(!inputAnswer.equals(correctAnswer)) { //is it the wrong answer
                        numIncorrect++;
                        topPanel.setAnswer("");
                    }
                    else {
                        numIncorrect = 0;
                        isCorrect = true;
                        if(isTeam1) {
                            team1Score += question.getPoints();
                        }
                        else {
                            team2Score += question.getPoints();
                        }
                    }
                }
                else {

                }
                topPanel.setTimer(cQuestion.getTime() - timeElapsed);
            }
            isTeam1 = !isTeam1;
        }
    }

    class GameTimer extends TimerTask {
        public void run() {
            System.out.println("Timer: " + timeElapsed);
            timeElapsed++;
            topPanel.setTimer(cQuestion.getTime() - timeElapsed);
        }
    }

    public void setTimer(int seconds) {
        System.out.println("Timer has started");
        timer = new java.util.Timer();
        timer.schedule(new GameTimer(), 0, 1000);
    }
}

顶级面板代码:

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

public class TopPanel extends JPanel implements KeyListener {
    JLabel questionLabel = new JLabel("Test Question");
    JTextField answerLabel = new JTextField("Answer label");
    JTextField timer = new JTextField("Timer Label");
    JTextField team1 = new JTextField("Team 1: 0");
    JTextField team2 = new JTextField("Team 2: 0");

    JPanel teamScores = new JPanel();

    //timer.setEditable(false);
    //team1.setEditable(false);
    //team2.setEditable(false);
    //answerLabel.setEditable(false);

    String inputString = "";
    boolean doneInputting = false;

    GridLayout scoresLayout = new GridLayout(2,1);
    GridLayout topLayout = new GridLayout(1,4);

    public TopPanel() {
        teamScores.setLayout(scoresLayout);
        teamScores.add(team1);
        teamScores.add(team2);
        this.setLayout(topLayout);
        this.setSize(getWidth(), 100);
        this.add(questionLabel);
        this.add(answerLabel);
        this.add(timer);
        this.add(teamScores);

        Font topFont = new Font("Sans Serif", Font.PLAIN, 32);

        this.setFont(topFont);
    }

    public void setQuestion(String question) {
        questionLabel.setText(question);
    }

    public void setAnswer(String answer) {
        answerLabel.setText(answer);
    }

    public void setTimer(int time) {
        timer.setText(time + "");
    }

    public void setTeam1Score(int score) {
        team1.setText(score + "");
    }

    public void addTeam1Score(int score) {
        team1.setText(score + "");
    }

    public void setTeam2Score(int score) {
        team2.setText(score + "");
    }

    public String getInput() {
        if(doneInputting) {
            return inputString;
        }
        return "nothing";
    }

    public String getCurrentInput() {
        return inputString;
    }

    public void keyPressed(KeyEvent e) {

    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_9) {
            inputString += "9";
        }
        else if(e.getKeyCode() == KeyEvent.VK_8) {
            inputString += "8";
        }
        else if(e.getKeyCode() == KeyEvent.VK_7) {
            inputString += "7";
        }
        else if(e.getKeyCode() == KeyEvent.VK_6) {
            inputString += "6";
        }
        else if(e.getKeyCode() == KeyEvent.VK_5) {
            inputString += "5";
        }
        else if(e.getKeyCode() == KeyEvent.VK_4) {
            inputString += "4";
        }
        else if(e.getKeyCode() == KeyEvent.VK_3) {
            inputString += "3";
        }
        else if(e.getKeyCode() == KeyEvent.VK_2) {
            inputString += "2";
        }
        else if(e.getKeyCode() == KeyEvent.VK_1) {
            inputString += "1";
        }
        else if(e.getKeyCode() == KeyEvent.VK_0) {
            inputString += "0";
        }
        else if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            inputString = inputString.substring(0, inputString.length()-1);
        }
        else if(e.getKeyCode() == KeyEvent.VK_T) {
            inputString += "TRUE";
        }
        else if(e.getKeyCode() == KeyEvent.VK_F) {
            inputString += "FALSE";
        }
        else if(e.getKeyCode() == KeyEvent.VK_P) {
            inputString += "π";
        }
        else if(e.getKeyCode() == KeyEvent.VK_S) {
            inputString += "√";
        }
        else if(e.getKeyCode() == KeyEvent.VK_ENTER) {
            doneInputting = true;
        }
        else if(e.getKeyCode() == KeyEvent.VK_SLASH) {
            inputString += "/";
        }
        setAnswer(inputString);
    }
}

1 个答案:

答案 0 :(得分:1)

您在while循环的每次迭代中都会启动一个新的Timer对象,因此每次在循环内创建一个新的Timer实例时,这会以额外的速度提前timeElapsed字段。解决方法是不要这样做,只使用一个Timer,或者在创建一个Timer之前停止Timer,....但是说了这么多,你在代码中遇到了其他重大问题,包括:

  • 这是一个Swing应用程序,您不应该使用java.util.Timers,而是使用javax.swing.Timers或&#34; Swing Timers&#34;。原因是Swing Timers与Swing事件线程配合良好,而Utility Timers则没有,这可能导致出现间歇性和极难调试的错误。
  • 您不应该使用while循环,因为这会阻止Swing事件线程(或者#T;事件调度线程和#34;的EDT),从而冻结GUI。而是使用你的Timer以及状态机设计来防止需要while循环。

如果您需要更详细的帮助,请回复上述评论,并帮助我们处理minimal example program,我们可以自行运行和修改。我们不希望看到您的整个程序,也不想要链接,而是向我们展示您问题的最小程序。