我查遍了整个网络,没有找到解决我的问题的方法。对于 AP Comp Sci 项目,我正在制作一组游戏,这些游戏将从带有 JButtons 的 JFrame 运行。我已准备好游戏以及 Action 监听器,但游戏无法正常启动。 JFrame 和 JButtons 也都设置正确。
private static class TetListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
GameCenter.quit();
GameCenter.startTetris();
}
}
GameCenter.quit() 除了运行 JFrame.dispose() 和 GameCenter.startTetris() 之外什么也不做;构造一个新的俄罗斯方 block 对象,然后运行 play() 方法来开始游戏。所有俄罗斯方 block 都已正确编码,并且在主方法(在 Action 监听器之外)中运行时可以正常工作。但是当我将它放入 ActionListener 中时,它就无法正确构造。我将问题归结为:
public BlockDisplay(BoundedGrid<Block> board)
{
this.board = board;
grid = new JPanel[board.getNumRows()][board.getNumCols()];
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() // <<<<<<<<<<------------------- Problem Here
{
public void run()
{
createAndShowGUI(); // <<<<<<<<<<<<-------- Never Run
}
});
//Wait until display has been drawn
try
{
while (frame == null || !frame.isVisible()) // <<<<<<<-------- Never Resolved
{
Thread.sleep(1);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
System.exit(1);
}
}
所以程序总是挂起。我还制作了一个使用 SwingUtilities.invokeLater 的 Pacman 游戏,所以它也不起作用。我不明白为什么会发生这种情况或如何解决它。
感谢任何帮助。如果您需要更多信息,请告诉我。
最佳答案
如果运行 SwingUtilities.invokeLater
的线程已经是 swing 事件线程,并且您在此 while 循环中运行,是的,您的应用程序将挂起。
摆脱 while 循环。
关于java - ActionListener 和 SystemUtil.invokeLater 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066304/