How to pause/delay, a specific part of my code

孤人 提交于 2021-02-05 11:47:05

问题


I have a paintComponent method, inside a class.It makes a grid of 10*10. And I want to lower the frame rate, so that every time the function colors a rectangle in the grid, I can see the progression

    public void paint(Graphics g1) {
        super.paint(g1);
        Graphics2D g= (Graphics2D) g1;
        
        for(Object a: Maze_Generator.list) {
            Cell c =(Cell)a;
            if(c.top())
                g.drawLine(c.x(), c.y(), c.x()+c.length(), c.y());
            if(c.bottom())
                g.drawLine(c.x(), c.y()+c.length(),c.x()+c.length(),c.y()+c.length());
            if(c.left())
                g.drawLine(c.x(), c.y(), c.x(), c.y()+c.length());
            if(c.right())
                g.drawLine(c.x()+c.length(), c.y(), c.x()+c.length(), c.y()+c.length());
            
// I wish to delay the following code by a second, so that I can see as the square gets coloured one by one.
            if(c.visited()) {
                g.setColor(Color.cyan);
                g.fillRect(c.x()+1, c.y()+1, c.length()-1, c.length()-1);
                g.setColor(Color.black);
                
            }
        }   

I tried using Thread.sleep(), but for some reasons the App freezes, and UI crashes(I only see JFrame, with white background,and it does not close) But the program still runs in Background

try{Thread.sleep(2000);}catch(Exception e){ e.printStackTrace();}
            if(c.visited()) {
                g.setColor(Color.cyan);
                g.fillRect(c.x()+1, c.y()+1, c.length()-1, c.length()-1);
                g.setColor(Color.black);

Any Suggestions?


回答1:


The problem is that when you use the Thread.sleep() method, it stops the thread's work, and with that freezes your program. The solution involves asynchronous programming. In java we can create another thread to preform the task that takes time, and that we want to use Thread.sleep() in.

With the release of lambda expressions in Java 8, we can use this syntax:

Thread newThread = new Thread(() -> {
    // Code that you want to perform asynchronously
});
newThread.start();



回答2:


I think your program should have two treads:

  • GUI thread (Used for rendering GUI)
  • Logic thread (Used for making some logical judgement) GUI thread will have a updateGUI method for passing message to GUI thraed and rendering based on the passed message.

please take a look following answers:

  • How to pass the message from working thread to GUI in java
  • Refreshing GUI by another thread in java (swing)


来源:https://stackoverflow.com/questions/65103141/how-to-pause-delay-a-specific-part-of-my-code

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