Swing GUI因未知原因冻结

时间:2013-09-15 21:03:56

标签: java swing user-interface

我正在创建一个java程序,为Grand Prix / Pinewood Derby创建阵容,比如比赛,然后输入分数后会找到决赛选手,并为他们分配一个车道/热门号码。

到目前为止,程序中的所有内容都完全符合我的要求,直到我到达试图创建入围者的部分。单击按钮/按回车键输入最终得分后,我的GUI冻结。以下是冻结之前的代码:

//allows user to enter the places for each car in each heat in each round
void enterScores() {
    if(indexCount == 0 || (indexCount) % numLanes == 0) {
        textArea.append("\nRound " + (roundCount + 1) + " Heat " + (heatCount+1) + ": ");
    }
    userResponse.setText("");
    prompt.setText(holderNameArray[roundCount][indexCount] + ": ");
    textArea.append("\n" + holderNameArray[roundCount][indexCount] + ": ");
    userResponse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            holderScoreArray[roundCount][indexCount] = Integer.parseInt(userResponse.getText());
            textArea.append("" + holderScoreArray[roundCount][indexCount]);
            indexCount++;
            for(ActionListener act : enter.getActionListeners()) {
                enter.removeActionListener(act);
            }
            for(ActionListener act : userResponse.getActionListeners()) {
                            userResponse.removeActionListener(act);
                        }
            repeatEnterScores();
        }
    });
    enter.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            holderScoreArray[roundCount][indexCount] = Integer.parseInt(userResponse.getText());
            textArea.append("" + holderScoreArray[roundCount][indexCount]);
            indexCount++;
            for(ActionListener act : enter.getActionListeners()) {
                enter.removeActionListener(act);
            }
            for(ActionListener act : userResponse.getActionListeners()) {
                            userResponse.removeActionListener(act);
                        }
            repeatEnterScores();
        }
    });

}
//helps repeat enterScores() due to anon class restrictions
//checks to change the number of heats/rounds
void repeatEnterScores() {
    if((indexCount) % numLanes == 0 || indexCount == numCars) {
        heatCount++;
    }
    if(indexCount == numCars) {
        indexCount = 0;
        heatCount = 0;
        roundCount++;
    }
    if(roundCount < numRounds) {
        enterScores();
    } else {
        textArea.setText("You may now click the Scores tab to see the scores you have just entered.");
        scoresPanelSetup();
    }
}

它曾经不会冻结并继续,但会在以后的地方冻结。我是初学者,所以我不确定为什么它现在冻结了。如果您需要更多代码/信息,请告诉我们。每当我调试它时,我的所有代码都会很好地执行,这只是gui遇到问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您尝试在EDT(事件调度线程)上执行长时间操作,GUI可能会挂起。您可以使用SwingWorker来避免这种情况。 SwingWorker有两个方法,即doInBackground()和done()。您应该在doInBackground()方法中进行计算并在done()方法中更新UI。您可以从此处了解有关SwingWorker的更多信息http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html