2011-05-20 38 views
1

我看遍了整个网络,发现没有解决我的问题。对于AP Comp Sci项目,我制作了一套游戏,这些游戏将从JFrame和JButtons运行。我已经准备好了游戏,还有动作听众,但游戏不会正常启动。 JFrame和JButton都安装正确。ActionListener和SystemUtil.invokeLater的问题

private static class TetListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     GameCenter.quit(); 
     GameCenter.startTetris(); 
    } 
} 

GameCenter.quit()什么也不做,但运行JFrame.dispose(),和GameCenter.startTetris();构造一个新的Tetris对象,然后运行play()方法来启动游戏。所有的俄罗斯方块都编码正确,并且在主方法中运行时(在actionlistener之外)正常工作。但是一旦我将它放入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游戏,所以它也不起作用。我无法弄清楚为什么会发生这种情况,或者如何解决这个问题。

任何帮助表示赞赏。让我知道你是否需要更多信息。

+0

''公共BlockDisplay(BoundedGrid 板)'有没有被调用? – 2011-05-20 00:36:04

+0

是的。俄罗斯方块在ActionListener之外完美工作,就像它应该那样。 – 2011-05-20 01:05:45

回答

2

如果运行SwingUtilities.invokeLater的线程已经是swing事件线程,并且在此while循环运行yup,则应用程序将挂起。

摆脱while循环。

+0

好吧,那固定的吃豆子,但俄罗斯方块requries循环到那里,否则它开始,虽然一些其他例外。有任何想法吗? – 2011-05-20 00:52:39

+0

发布例外。 – 2011-05-20 01:45:39

+0

如果swing准备好显示您的GUI,则您的游戏循环应该开始。你可以注册一个监听器,检查JFrame/Frame类 – 2011-05-20 01:46:06