6

我有一个用 Java 制作的二十一点游戏,我想通过单击一个按钮来表示游戏开始。我所有的动作侦听器都可以正常工作,但问题在于如果游戏没有完全在 actionPerformed 方法中运行,我无法弄清楚如何启动游戏。显然,在 actionPerformed 方法中连续运行的函数将有效地禁用我的 GUI 的其余部分。这是一个代码片段......

go.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
                 // START GAME SOMEHOW but must run outside of action listener
        }
    });
4

3 回答 3

7

Obviously, a function continuously running within the actionPerformed method will effectively disable the rest of my GUI.

This is a valid observation and shows that you have understand the fundamental rule when working with Swing.

Your game is most likely event driven (correct me if I'm wrong) so the action performed by the button should just set the program in a new state, waiting for further events. This is nothing that should be time consuming, and is typically done directly by the EDT.

Of course, if you want to do a fancy start-new-game animation, that needs to be performed in a separate thread, in which case you simply start the animation thread (I would recommend using a SwingWorker though) from within the actionPerformed method, and then return.

In code, I imagine it would look something like this:

go.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        // Remove the menu components
        someJPanel.removeAll();

        // Show the game table
        someJPanel.add(new GamePanel());

        someJPanel.revalidate();
        someJPanel.repaint();

        // done. Wait for further user actions.
    }
});
于 2012-05-11T20:41:46.077 回答
1

我相信您想扩展javax.swing.SwingWorker

非 ui 启动功能将在doInBackground中运行,并且在完成更新 ui 时将调用done方法。

javadoc 类描述中甚至还有一个示例,可以用启动时发生的情况更新进度条。

于 2012-05-11T21:02:15.233 回答
1

您的游戏可能应该从它自己的线程开始并自行管理(很难说),但是为了让您开始您的游戏,您可以在一个新的“外部”线程中开始您的游戏,在您的 actionPerformed 中是这样的:

public void actionPerformed(ActionEvent e) {
    Thread thread = new Thread("Game thread") {
        public void run() {
            startGame(); //or however you start your game
        }
    };
    thread.start();
}
于 2012-05-11T20:29:00.267 回答