2

我正在尝试创建一个程序,该程序将通过在每次排序循环时绘制一组代表数组的条来可视化不同的排序算法。但是,当我从排序器类中设置数组时,它会重新绘制面板,似乎它只在第一次和最后一次迭代中调用paintComponent(),而不是显示中间的步骤。

这是调用 setNumberArray() 方法的排序代码:

public void bubbleSort() {
    int[] x = getNumberArray();
    boolean doMore = true;
    while (doMore) {
        doMore = false;
        for (int count = 0; count < x.length - 1; count++) {
            if (x[count] > x[count+1]) {
               int temp = x[count];  x[count] = x[count+1];  x[count+1] = temp;
               doMore = true;
            }
        }
        // Update the array
        SorterGUI.getSorterPanel().setNumberArray(x);
        // Pause
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Sorter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

哪个电话:

public void setNumberArray(int[] numberArray) {
    this.numberArray = numberArray;
    repaint();
}

最后绘制条形图:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    int length = numberArray.length;
    Graphics2D g2d = (Graphics2D) g;

    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, getWidth(), getHeight());

    g2d.setColor(Color.gray);
    for(int count = 0; count < length; count++) {
        g2d.fill3DRect((getWidth() / length) * (count + 1), 0, 
               getWidth() / length, getHeight() - (numberArray[count] * 3), 
               true);
        playSound(numberArray[count]);
    }
    System.out.print(".");
}

我知道它不会在两者之间重新绘制(有或没有延迟),因为它只打印一个“。” 当我开始排序时。

4

2 回答 2

2

立即忘记油漆,因为那不会解决您的问题。问题是您在 EDT 上调用 Thread.sleep,主 Swing 线程称为事件调度线程,这将使您的 Swing 应用程序进入睡眠状态(正如您所发现的那样)。取而代之的是使用 Swing Timer 来延迟,一切都会很好。要么这样做,要么在后台线程中执行 Thread.sleep。

于 2011-02-07T03:05:13.027 回答
1

您可以使用JComponent.paintImmediately强制立即绘画

于 2011-02-07T01:48:53.867 回答