0
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.

  • This might be your issue: https://stackoverflow.com/questions/369823/java-gui-repaint-problem – Andrew Henle Aug 07 '17 at 15:48
  • You need to run `repaint();` method on EDT via `SwingUtilities.invokeLater` method. – tsolakp Aug 07 '17 at 15:54
  • Yes it actually is, and a revalidate() nailed it, thank you so much! – Oryol Uperi Aug 07 '17 at 16:01
  • `nothing in the window at all,` - you never make the frame visible. Use a Swing Timer for animation. Don't use a KeyListener. Instead use `Key Bindings. Don't override paint(). Custom painting is done be overriding paintComponent(). So many problems. Start by reading the [Swing Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/TOC.html). There are sections on all the above suggestions I made. – camickr Aug 07 '17 at 16:03

1 Answers1

1

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.