首页 > 解决方案 > 如何使用定时器和延迟更新 Java Swing GUI?

问题描述

我正在尝试使用 Java GUI 制作排序可视化器。我面临的问题是实时更新 GUI。例如,当我对初始数组进行洗牌时,我将调用以下洗牌和交换方法。我希望它重新绘制 GUI,然后在延迟后再次执行它,但它所做的只是完成 shuffleArray 方法,然后一次重新绘制它,显示没有“动画”。有什么更好的方法来解决这个问题?

   public void shuffleArray() {
        final int milliDelay = 1000;
        for (int i = NUM_BARS - 1; i >= 0; i--) {
            int rand = (int) (Math.random() * i);

            swap(i,rand, milliDelay);
        }
    }

    public void swap(int firstIndex, int secondIndex, int delay) {

        Timer timer = new Timer(delay, e -> {
            int temp = data[firstIndex];
            data[firstIndex] = data[secondIndex];
            data[secondIndex] = temp;

            barColors[firstIndex] = Color.RED;
            barColors[secondIndex] = Color.RED;

            repaint();

            barColors[firstIndex] = Color.WHITE;
            barColors[secondIndex] = Color.WHITE;
        });
        timer.setRepeats(false);
        timer.start();
    }

标签: javaswingsortinguser-interfacetimer

解决方案


推荐阅读