如何暂停/延迟,这是我代码的特定部分 [英] How to pause/delay, a specific part of my code

查看:72
本文介绍了如何暂停/延迟,这是我代码的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类内部有一个paintComponent方法,它形成10 * 10的网格.而且我想降低帧频,以便每次函数在网格中为矩形着色时,我都能看到进度

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

我尝试使用Thread.sleep(),但由于某些原因,该应用程序冻结,并且UI崩溃(我只看到JFrame,带有白色背景,并且不会关闭)但是该程序仍在后台运行

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

有什么建议吗?

推荐答案

问题是,当您使用 Thread.sleep()方法时,它将停止线程的工作,并冻结您的线程程序.该解决方案涉及异步编程.在Java中,我们可以创建另一个线程来执行耗时的任务,并希望在其中使用 Thread.sleep().

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.

随着Java 8中lambda表达式的发布,我们可以使用以下语法:

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

这篇关于如何暂停/延迟,这是我代码的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆