【问题标题】:Creating delay between GUI updates在 GUI 更新之间创建延迟
【发布时间】:2020-06-07 12:05:24
【问题描述】:

我正在尝试使用 Swing 在 Java 中创建排序可视化工具。到目前为止,我的程序询问用户他们选择的排序算法(我在这里排除了选择菜单的代码),然后直观地对未排序的数组进行排序。到目前为止,我为 GUI 测试目的实现的唯一排序算法是插入排序。

下面是插入排序算法:

public class InsertionSort extends Sorter { // Sorter is an abstract class
    @Override
    public void sort(ArrayVisualization array) { // ArrayVisualization object to change array values
        for (int i = 0; i < array.getArraySize(); i++) {
            int j = i - 1;
            int key = array.getArrayValue(i);
            while (j >= 0 && array.getArrayValue(j) > key) {
                array.delayedSwap(j, j+1); // calls delayedSwap method continually-PROBLEM
                --j;
            }
        }
    }

    @Override
    public String toString() {
        return "Insertion Sort";
    }
}

我无法正确显示各种指数之间的互换。起初,我尝试使用Thread.sleep() 在交换值时让线程短暂进入睡眠状态。这不可避免地最终冻结了 EDT。通过 Stack Overflow 搜索后,我发现了在进行 GUI 修改时推荐的 Swing Timer。

当我使用 Swing Timer 对 shuffleArray() 中的数组进行 改组 时,它工作得非常好,我可以看到每个值都被延迟交换(目前,shuffleArray() 中使用的部分Swing Timer 被评论是因为我后来决定不显示延迟的洗牌部分)。当我使用 Swing Timer 以类似的方式实现 delayedSwap() 方法时,数组自身稍微排序,但随后突然停止。数组作为一个整体保持未排序。

delayedSwap() 被调用了适当的次数,并且在没有 Swing Timer 的情况下进行测试时,插入排序算法也可以正常工作。

谁能告诉我为什么我在delayedSwap() 中遇到了 Swing Timer 这个问题?我尝试使用SwingWorker 并在delayedSwap() 中创建一个新线程,然后将其置于睡眠状态。我有点认为这与我在另一个类的循环中反复调用delayedSwap() 有关,但我不明白如何实现delayedSwap(),因为它用于所有排序算法(大致)。如果这无法解决,还有其他选择吗?

下面是ArrayVisualizer 的代码,其中包含delayedSwap()。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class ArrayVisualization extends JPanel {
    private int[] array;
    private static final int BAR_WIDTH = 5;
    private final static int WIN_WIDTH = 1280;
    private final static int WIN_HEIGHT = 720;
    private static final int NUM_BARS = WIN_WIDTH / BAR_WIDTH;
    //private static final int SWAP_DELAY = 1;


    public void arrayScreen() {
        JFrame frame = new JFrame("Sorting Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setLayout(new BorderLayout());

        ArrayVisualization panel = new ArrayVisualization();
        frame.add(panel);

        frame.setSize(WIN_WIDTH, WIN_HEIGHT);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
    }

    public int getArraySize() {
        return this.array.length;
    }

    public int getArrayValue(int x) {
        return this.array[x];
    }

    public ArrayVisualization() { 
        array = new int[NUM_BARS];
        for (int i = 0; i < NUM_BARS; i++) { // populate the array
            array[i] = i;
        }
        shuffleArray(); // shuffle
        InsertionSort sort = new InsertionSort();
        sort.sort(this); // sort
    }

    public void shuffleArray() {
        Random rand = new Random();

        for (int i = 0; i < NUM_BARS; i++) {
            int randIdx = rand.nextInt(NUM_BARS - 1); // create random indices to swap with
            int temp = array[randIdx];
            array[randIdx] = array[i];
            array[i] = temp;
        }
        repaint(); 

 /*       Timer timer = new Timer(1, new ActionListener() {
            private int counter;

            @Override
            public void actionPerformed(ActionEvent e) {
                int randomNumber = rand.nextInt(NUM_BARS - 1);

                int temp = array[counter];
                array[counter] = array[randomNumber];
                array[randomNumber] = temp;
                repaint();
                if (counter == NUM_BARS - 1) {
                    ((Timer)e.getSource()).stop();
                }
                counter++;
            }
        });
        timer.start();*/
    }

/* MAIN PROBLEM */
    public void delayedSwap(int idx1, int idx2) {
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                int temp = array[idx1];
                array[idx1] = array[idx2];
                array[idx2] = temp;
                repaint();
                ((Timer) e.getSource()).stop(); // so that timer terminates after 1 swap
            }
        });
        timer.start();
    }


    @Override
    public void paintComponent(Graphics g) {
        Graphics2D graphics = (Graphics2D) g;
        super.paintComponent(graphics);


        graphics.setColor(Color.BLACK);
        for (int i = 0; i < NUM_BARS; i++) {
            int height = array[i] * 2;
            int xBegin = i + (BAR_WIDTH - 1) * i;
            int yBegin = WIN_HEIGHT - height;

            graphics.fillRect(xBegin, yBegin, BAR_WIDTH, height);
        }
    }
}

谢谢!

【问题讨论】:

    标签: java swing timer


    【解决方案1】:

    您错误地使用了计时器。了解将使用 Swing 计时器代替 while 循环,因此重复调用计时器的 actionPerformed 方法,就像在循环中一样,但具有 Swing 可容忍的延迟。相反,您自己的 Timer 会被重新创建并重复重新启动,并且只调用一次并停止,完全阻止它执行它应该执行的操作。

    解决方案:

    • 摆脱 for 循环和 while 循环
    • 使用 Timer 执行 for 循环和 while 循环的内部操作
    • 不要立即停止 Timer,而是在 if 条件内停止 - 当循环应该结束时。
    • 使用 if 块来模拟外部 for 循环和内部 while 循环功能

    例如,您的排序方法可能看起来像这样简单:

    @Override
    public void sort(ArrayVisualization array) { // ArrayVisualization object to change array values
        int timerDelay = 400;  // or however many msecs desired
        new Timer(new TimerListener(array), timerDelay).start();        
    }
    

    还有……

    class TimerListener implements ActionListener {
        private ArrayVisualization array;
        private int arrayIndex = 0;
        private int innerIndex = 0;
        int key = 0;
        private boolean insideInnerLoop = false;
    
        public TimerListener(ArrayVisualization array) {
            this.array = array;
        }
    
        public void actionPerformed(ActionEvent e) {
    
            if (!insideInnerLoop) {
                insideInnerLoop = true;
                innerIndex = arrayIndex - 1;
                key = array.getArrayValue(arrayIndex);
            } else {
                if (innerIndex < 0 || array.getArrayValue(innerIndex) > key) {
                    insideInnerLoop = false;
                    arrayIndex++;
                    break;
                } else {
                    // swap code here
                    innerIndex--;
                }
            }
            // ......
    
    
            if (arrayIndex >= array.getArraySize()) {
                ((Timer) e.getSource()).stop();
            }
        }
    }
    

    (代码未测试...)


    如果您希望保留自己的循环,另一种选择是使用 SwingWorker 作为后台线程,并在 worker 的 doInBackground 方法中使用 Thread.sleep 或类似的延迟代码。这也可以,但需要注意不要违反 Swing 线程规则,包括您应该使用发布/处理方法对将中间结果发送回 GUI 进行显示。

    【讨论】:

    • 谢谢你,我明白你的意思。但是因为我要处理多种排序算法,所以用计时器而不是循环重新创建所有这些算法会有点乏味。有没有其他方法可以以某种方式延迟交换部分而不重构算法?不过与此同时,我会尝试您推荐的方法。谢谢!
    • @GarbageCollector 一旦你掌握了窍门,它就不会乏味了。您只是重新排列代码,而不是重新创建它。这是规范的解决方案,我敦促您遵循它。
    • @GarbageCollector:另一种选择是使用 SwingWorker 作为后台线程,这将允许您继续使用自己的循环,但在执行该路线时必须格外小心 Swing 线程问题.
    • 谢谢!看来 actionPerformed 已经取代了 for 循环。那么原始算法中出现的while循环呢?该建议说我需要在侦听器中放置“if”块。但是,如何使用 if 语句模拟 while 循环?
    • @GarbageCollector:是的,您可以模拟两个循环。 actionPerformed 不断重复,并且根据计时器的状态(它所持有的实例字段所持有的值),此重复可以表示 for 循环或嵌套的 if 循环。只有在“逻辑”while 循环完成时才会增加 for 循环计数器,然后重新设置 while 循环循环条件。
    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 2020-07-15
    • 2014-10-02
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多