Java 在具有延迟的循环中重新绘制JPanel
我正试图创建一个程序,通过在每次排序循环中绘制一组表示数组的条形图来可视化不同的排序算法。但是,当我在sorter类中设置数组时,该类会重新绘制面板,它似乎只在第一次和最后一次迭代中调用paintComponent(),而没有显示中间的步骤 下面是调用setNumberArray()方法的排序代码: 最后绘制钢筋:Java 在具有延迟的循环中重新绘制JPanel,java,swing,sorting,jpanel,repaint,Java,Swing,Sorting,Jpanel,Repaint,我正试图创建一个程序,通过在每次排序循环中绘制一组表示数组的条形图来可视化不同的排序算法。但是,当我在sorter类中设置数组时,该类会重新绘制面板,它似乎只在第一次和最后一次迭代中调用paintComponent(),而没有显示中间的步骤 下面是调用setNumberArray()方法的排序代码: 最后绘制钢筋: protected void paintComponent(Graphics g) { super.paintComponent(g); int length = n
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(".");
}
受保护的组件(图形g){
超级组件(g);
int length=numberArray.length;
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.white);
fillRect(0,0,getWidth(),getHeight());
g2d.setColor(Color.gray);
对于(int count=0;count
我知道它不会在两者之间重新绘制(有或没有延迟),因为当我开始排序时,它只打印一个“.”。您可以使用
JComponent.paintimmediate
强制立即绘制立即忘记绘制,因为这不会解决您的问题。问题是您正在EDT上调用Thread.sleep,这是一个主Swing线程,称为事件调度线程,这将使您的Swing应用程序进入睡眠状态(如您所发现的)。相反,使用一个摆动计时器来延迟,一切都会很好。要么那样做,要么做你的线程。在后台线程中睡眠。可能重复。。。
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(".");
}