【问题标题】:How to pause/delay, a specific part of my code如何暂停/延迟,我的代码的特定部分
【发布时间】:2021-03-14 02:53:47
【问题描述】:

我有一个paintComponent 方法,在一个类中。它生成一个10*10 的网格。 而且我想降低帧率,这样每次函数给网格中的一个矩形上色时,我都能看到进度

    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,白色背景,它没有关闭) 但程序仍然在后台运行

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

有什么建议吗?

【问题讨论】:

    标签: java timer delay java-threads timedelay


    【解决方案1】:

    我认为你的程序应该有两个步骤:

    • GUI 线程(用于渲染 GUI)
    • 逻辑线程(用于做一些逻辑判断) GUI 线程将具有 updateGUI 方法,用于将消息传递给 GUI 线程并根据传递的消息进行渲染。

    请看以下答案:

    【讨论】:

      【解决方案2】:

      问题在于,当您使用Thread.sleep() 方法时,它会停止线程的工作,从而冻结您的程序。 该解决方案涉及异步编程。在java中,我们可以创建另一个线程来执行需要时间的任务,并且我们想在Thread.sleep()中使用。

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

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

      【讨论】:

      • 正确,但通常最好使用现代 Java 中内置的 Executors 框架,而不是直接操作 Thread
      • 我试过这个方法,但是它并没有执行里面的 grapic/draw 代码。当我尝试将一些文本打印到控制台时它可以工作,但它不执行 fillRect 命令。我该怎么办?
      • 调试的时候能看到执行吗?
      • 是的,当我在新线程中放置一些打印代码时,它工作正常并打印到控制台,只有像(fillRect 和其他)这样的图形方法似乎不起作用
      • 经过一番搜索,我发现Graphics2D只能单线程工作。但他们为您的问题提供了一些解决方案。看这里:stackoverflow.com/questions/16545075/…
      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2012-11-21
      • 1970-01-01
      相关资源
      最近更新 更多