【问题标题】:Thread in swing doesn't always run摆动中的线程并不总是运行
【发布时间】:2018-01-14 23:51:15
【问题描述】:
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 中使用线程可能会导致并发问题,我想知道是否是这种情况,以及我应该做些什么来纠正它。谢谢。

【问题讨论】:

  • 你需要通过SwingUtilities.invokeLater方法在EDT上运行repaint();方法。
  • 是的,确实如此,并且 revalidate() 成功了,非常感谢!
  • nothing in the window at all, - 你永远不会让框架可见。使用 Swing Timer 制作动画。不要使用 KeyListener。而是使用`键绑定。不要覆盖paint()。自定义绘画通过覆盖paintComponent() 完成。这么多问题。首先阅读Swing Tutorial。我提出的所有上述建议都有部分内容。

标签: java multithreading swing


【解决方案1】:

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

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

虽然看来我对 Swing 的理解还太浅,但我还是得复习一下教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多