私は、並べ替えループが発生するたびに配列を表す一連の棒を描画することによって、さまざまな並べ替えアルゴリズムを視覚化するプログラムを作成しようとしています。しかし、パネルを再描画するソータークラス内から配列を設定すると、最初と最後の繰り返しでpaintComponent()が呼び出され、その間にステップが表示されないようです。遅延を伴うループでJPanelを再ペイントする
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(".");
}
私はそれがないと知っている。ここ
はsetNumberArray()メソッドを呼び出して、ソートコードです(遅延の有無にかかわらず)1つしか印刷しないので、その間で再ペイントします。私がソートを開始するとき。
可能な複製... http://stackoverflow.com/questions/4120528/repaint-in-a-loop –