摆动中的线程并不总是运行

时间:2017-08-07 15:44:18

标签: java multithreading swing

public class Interface extends JFrame
{
    public Interface() throws  InterruptedException 
    {   
        //windowsetup
        pan = new MainPanel();
        Thread t = new Thread(pan);
        t.start();
        add(pan);
        addKeyListener(pan);
    }
    public static void main(String[] Args) throws InterruptedException 
    {
        Interface proj = new Interface();
    }
}
////////
public class MainPanel extends JPanel implements KeyListener, Runnable
{
    public void paint(Graphics g)
    {
        //painting
    }
    public void run()
    {
        while(true)
        {
            this.repaint();
            //other codes
            try 
            {
                Thread.sleep(10);
            }
            catch (InterruptedException e) 
            {
                e.printStackTrace();
           }
         }
    }
}

我有一个看起来像这样的代码。当我在Eclipse中按下运行按钮时,有时它可以正常工作,但有时窗口中根本没有任何东西,没有任何颜色,键也不起作用。

我听说在GUI中使用线程可能会导致并发问题,我想知道是不是这样,我应该怎么做才能纠正它。感谢。

1 个答案:

答案 0 :(得分:1)

stackoverflow.com/questions/369823/java-gui-repaint-problem

我发现这正是我的情况,并且解决方案有效。

虽然看起来我对Swing的理解还太浅薄,但我必须仔细阅读教程。

相关问题