简体   繁体   中英

Thread in swing doesn't always run

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();
           }
         }
    }
}

I have a code that looks like this. When I press the run button in Eclipse, sometimes it works properly, but sometimes the there would be nothing in the window at all, nothing painted and keys doesn't work.

I heard that using threads in GUI might cause concurrency problems, and I wonder if this is the case, and what I should do to correct it. Thanks.

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

I found that this is exactly my case, and the solutions worked.

Though it appears my understanding to Swing is yet too shallow, I must go over the tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM