暂停程序直到单击JButton

时间:2013-03-11 04:02:50

标签: java swing jbutton

我四处寻找,但无法得到明确的答案。我写了一个需要暂停的游戏,直到用户点击按钮做出决定,然后继续执行。有没有标准的方法来做到这一点?

我见过类似的问题,指的是使用'wait()'和'notify()',但我不确定我是否需要添加更多的线程,特别是因为我没有执行复杂或耗时的操作代码。

我应该澄清它是一个棋盘游戏的计算机版本,所以只不过是一个包含某些组件的框架。以下是我正在尝试做的一些事情,谢谢你们:

public class TreasureHunterFrame extends javax.swing.JFrame
{

    public TreasureHunterFrame()
    {
        initComponents();

        startNewGame();
    }

    private void startNewGame()
    {
        ...
        // User asked to click button while this method is running
        synchronized (this) // wait until Stay of Leave button is clicked
    {
        try 
        {
            while (!userHasMadeDecision)
        this.wait();
        }
        catch (InterruptedException ie)
        {
        }
        }
        ....

    }

    private void userStayButtonActionPerformed(java.awt.event.ActionEvent evt)
    {                                
        userHasMadeDecision = true;
        userLeaving = false;
        synchronized (this)
        {
        notifyAll();
        }
    }          

    public static void main(String args[])
    {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TreasureHunterFrame().setVisible(true);
            }
        });
    }
}

0 个答案:

没有答案