並べ替えがループするたびに、配列を表す一連のバーを描画することにより、さまざまな並べ替えアルゴリズムを視覚化するプログラムを作成しようとしています。ただし、パネルを再描画するソータークラス内から配列を設定すると、最初と最後の反復でのみ 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(".");
}
「。仕分けを始めるとき。