0

正如我在上一篇文章中与 Inerdia 讨论的那样
当我在某个 JPanel 中(EDT 肯定——我检查了方法检查)然后我调用了一些动画线程(线程扩展线程)来启动时,有些东西仍然很奇怪。通过检查我不在 EDT 上的线程。
所以我想我应该是因为动画应该在 EDT 上,所以我用 runnable 和 invokeAndWait() 包装了 animate 方法,但仍然在我不在 EDT 上的动画线程中得到了它,同时调用了我之前说的那个代码在 EDT 上,所以,我的 invokeLater 似乎没有将该动画放在 EDT 上?这是为什么?

相关代码(在使用 runnable 包装 animate 方法并稍后传递给调用之前:
因此,在 JPanel 上有一行:

Animate(trainRailRoadTrack);  

实现是:

void Animate(ArrayList<RailroadSquare> i_TrainRailRoadTrack) {
    ArrayList<JPanelRailoadSquare> playerRailoadPanelsTrack = getRelevantRailroads(i_TrainRailRoadTrack);
    new SuspendedAnimation(playerRailoadPanelsTrack).start();
    jPanelBoard1.GetGameManager().EmptyPlayerSolution();
}

private class SuspendedAnimation extends Thread
{
    private ArrayList<JPanelRailoadSquare> m_PlayerRailoadPanelsTrack;

    public SuspendedAnimation(ArrayList<JPanelRailoadSquare> i_PlayerRailoadPanelTrack)
    {
        m_PlayerRailoadPanelsTrack = i_PlayerRailoadPanelTrack;
    }

    @Override
    public void run()
    {
       m_IsAnimationNeeded = true;
       for (JPanelRailoadSquare currRailoadSquare: m_PlayerRailoadPanelsTrack)
       {
           System.out.println("Is on Event dispatch thread: "+SwingUtilities.isEventDispatchThread());
           currRailoadSquare.SetGoingTrain();
           repaint();                            
           try
           {
               Thread.sleep(150);

           }
           catch (InterruptedException e){}
           currRailoadSquare.UnSetGoingTrain();
           repaint();                       
    }
}
4

1 回答 1

1

SuspendedAnimation.run()你的内心不在美国东部时间。那是您需要使用的地方invokeLater(),而不是在调用时Animate()

@Override
public void run()
{
    // We're outside the EDT in most of run()
    m_IsAnimationNeeded = true;
    for (JPanelRailoadSquare currRailoadSquare: m_PlayerRailoadPanelsTrack)
    {
        SwingUtilities.invokeAndWait(new Runnable() {
            // The code that "talks" to Swing components has to be put on
            // the EDT
            currRailoadSquare.SetGoingTrain();
            repaint();
        });

        // We want to keep sleeping outside the EDT.
        try
        {
            Thread.sleep(150);
        }
        catch (InterruptedException e){}

        SwingUtilities.invokeAndWait(new Runnable() {
            currRailoadSquare.UnSetGoingTrain();
            repaint();                       
        }
    }
}
于 2011-10-23T18:10:36.220 回答