Repaint is not functioning properly as required

匆匆过客 提交于 2019-12-02 05:15:13

Your problem appears to be a Swing threading issue as you appear to be calling Thread.sleep(...) on the Swing event thread. Doing this will lock the entire thread, freezing your application. Don't do this, but use a Swing Timer instead.

As an aside, you don't want to override the update() method for Swing GUI's as that's mainly for AWT GUI's, unless you're changing the application's Look and Feel in mid run.


Edit
You ask:

I understand that calling Thread.sleep() is undesirable and it is better to use timers. But the thing is that when I run the MatrixBoard individually, it works perfectly well. The thread issue is not faced here. Please explain if possible.

When you call it by itself, the main application is not being run on the Swing thread (which is not something that should be done -- all Swing apps should be run on the Swing event thread), and so your code seems to work. Once you force it to run on the Swing event thread, it freezes.

All Swing GUI's should be queued onto the event thread using SwingUtilities.invokeLater(new Runnable() {...});


Edit 2

Watch what happens when you change this:

public static void main(String [] args){
    MatrixBoard b = new MatrixBoard();      
}

to the more appropriate code:

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        MatrixBoard b = new MatrixBoard();      
      }
    });
}

I'll bet your MatrixBoard will not freeze (although I haven't tested it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!